/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar
4988.10.3 by John Arbash Meinel
Merge bzr.dev 5007, resolve conflict, update NEWS
1
# Copyright (C) 2005-2010 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
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
21
from bzrlib.lazy_import import lazy_import
22
lazy_import(globals(), """
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.
23
import cStringIO
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
24
import sys
1551.12.8 by Aaron Bentley
Add merge-directive command
25
import time
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
26
1773.4.2 by Martin Pool
Cleanup of imports; undeprecate all_revision_ids()
27
import bzrlib
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
28
from bzrlib import (
2376.4.22 by Jonathan Lange
Variety of whitespace cleanups, tightening of tests and docstring changes in
29
    bugtracker,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
30
    bundle,
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
31
    btree_index,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
32
    bzrdir,
4879.2.1 by Neil Martinsen-Burrell
switch should use directory services when creating a branch
33
    directory_service,
2225.1.1 by Aaron Bentley
Added revert change display, with tests
34
    delta,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
35
    config,
36
    errors,
2298.8.1 by Kent Gibson
Normalise ignore patterns to use '/' path separator.
37
    globbing,
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
38
    hooks,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
39
    log,
1996.3.5 by John Arbash Meinel
Cleanup, deprecated, and get the tests passing again.
40
    merge as _mod_merge,
1551.12.8 by Aaron Bentley
Add merge-directive command
41
    merge_directive,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
42
    osutils,
2796.2.5 by Aaron Bentley
Implement reconfigure command
43
    reconfigure,
3193.8.18 by Aaron Bentley
Move all rename-guessing into RenameMap
44
    rename_map,
2598.5.1 by Aaron Bentley
Start eliminating the use of None to indicate null revision
45
    revision as _mod_revision,
4789.28.3 by John Arbash Meinel
Add a static_tuple.as_tuples() helper.
46
    static_tuple,
2204.5.5 by Aaron Bentley
Remove RepositoryFormat.set_default_format, deprecate get_format_type
47
    symbol_versioning,
4766.2.1 by Alexander Sack
add --commit-time Option to built-in 'commit' command (LP: #459276)
48
    timestamp,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
49
    transport,
50
    ui,
51
    urlutils,
3586.1.20 by Ian Clatworthy
centralise formatting of view file lists
52
    views,
1836.1.26 by John Arbash Meinel
[merge] bzr.dev 1869
53
    )
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
54
from bzrlib.branch import Branch
2120.7.2 by Aaron Bentley
Move autoresolve functionality to workingtree
55
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.
56
from bzrlib.transport import memory
3936.3.40 by Ian Clatworthy
review feedback from jam
57
from bzrlib.revisionspec import RevisionSpec, RevisionInfo
2535.2.1 by Adeodato Simó
New SMTPConnection class, a reduced version of that in bzr-email.
58
from bzrlib.smtp_connection import SMTPConnection
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
59
from bzrlib.workingtree import WorkingTree
60
""")
61
5127.1.1 by Martin Pool
version-info is lazily loaded
62
from bzrlib.commands import (
63
    Command,
64
    builtin_command_registry,
65
    display_command,
66
    )
3921.3.9 by Marius Kruger
* add some blackbox tests and another whitebox test
67
from bzrlib.option import (
68
    ListOption,
69
    Option,
70
    RegistryOption,
71
    custom_help,
72
    _parse_revision_str,
73
    )
3874.1.4 by Vincent Ladeuil
Fixed as per Aarons' comment.
74
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
75
76
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
77
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
3586.1.32 by Ian Clatworthy
merge bzr.dev r3998
78
def tree_files(file_list, default_branch=u'.', canonicalize=True,
79
    apply_view=True):
5346.3.1 by Martin Pool
* `PathNotChild` should not give a traceback.
80
    return internal_tree_files(file_list, default_branch, canonicalize,
81
        apply_view)
1185.35.28 by Aaron Bentley
Support diff with two branches as input.
82
1185.85.12 by John Arbash Meinel
Refactoring AddAction to allow redirecting to an encoding file.
83
3586.1.34 by Ian Clatworthy
fix tree/path handling for add
84
def tree_files_for_add(file_list):
4301.2.2 by Aaron Bentley
Update style
85
    """
86
    Return a tree and list of absolute paths from a file list.
87
88
    Similar to tree_files, but add handles files a bit differently, so it a
89
    custom implementation.  In particular, MutableTreeTree.smart_add expects
90
    absolute paths, which it immediately converts to relative paths.
91
    """
92
    # FIXME Would be nice to just return the relative paths like
93
    # internal_tree_files does, but there are a large number of unit tests
94
    # that assume the current interface to mutabletree.smart_add
3586.1.34 by Ian Clatworthy
fix tree/path handling for add
95
    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
96
        tree, relpath = WorkingTree.open_containing(file_list[0])
4301.2.5 by Aaron Bentley
Move file_list updates after view_files check.
97
        if tree.supports_views():
98
            view_files = tree.views.lookup_view()
99
            if view_files:
100
                for filename in file_list:
101
                    if not osutils.is_inside_any(view_files, filename):
102
                        raise errors.FileOutsideView(filename, view_files)
4301.2.4 by Aaron Bentley
Further cleanups
103
        file_list = file_list[:]
4301.2.3 by Aaron Bentley
Clean up tree_add_files
104
        file_list[0] = tree.abspath(relpath)
3586.1.34 by Ian Clatworthy
fix tree/path handling for add
105
    else:
106
        tree = WorkingTree.open_containing(u'.')[0]
107
        if tree.supports_views():
108
            view_files = tree.views.lookup_view()
109
            if view_files:
110
                file_list = view_files
111
                view_str = views.view_display_str(view_files)
4210.1.1 by Ian Clatworthy
reword 'ignoring files outside view' message
112
                note("Ignoring files outside view. View is %s" % view_str)
4301.2.3 by Aaron Bentley
Clean up tree_add_files
113
    return tree, file_list
3586.1.34 by Ian Clatworthy
fix tree/path handling for add
114
115
3984.3.5 by Daniel Watkins
Changed from option type to helper function.
116
def _get_one_revision(command_name, revisions):
117
    if revisions is None:
118
        return None
119
    if len(revisions) != 1:
120
        raise errors.BzrCommandError(
121
            'bzr %s --revision takes exactly one revision identifier' % (
122
                command_name,))
123
    return revisions[0]
124
125
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
126
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)
127
    """Get a revision tree. Not suitable for commands that change the tree.
128
    
129
    Specifically, the basis tree in dirstate trees is coupled to the dirstate
130
    and doing a commit/uncommit/pull will at best fail due to changing the
131
    basis revision data.
132
133
    If tree is passed in, it should be already locked, for lifetime management
134
    of the trees internal cached state.
135
    """
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
136
    if branch is None:
137
        branch = tree.branch
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
138
    if revisions is None:
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
139
        if tree is not None:
140
            rev_tree = tree.basis_tree()
141
        else:
142
            rev_tree = branch.basis_tree()
143
    else:
3984.3.5 by Daniel Watkins
Changed from option type to helper function.
144
        revision = _get_one_revision(command_name, revisions)
145
        rev_tree = revision.as_tree(branch)
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
146
    return rev_tree
147
148
1658.1.9 by Martin Pool
Give an error for bzr diff on an nonexistent file (Malone #3619)
149
# XXX: Bad function name; should possibly also be a class method of
150
# WorkingTree rather than a function.
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
151
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
3586.1.32 by Ian Clatworthy
merge bzr.dev r3998
152
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
153
    apply_view=True):
1658.1.8 by Martin Pool
(internal_tree_files) Better docstring
154
    """Convert command-line paths to a WorkingTree and relative paths.
155
5346.4.2 by Martin Pool
Move internal_tree_files and safe_relpath_files onto WorkingTree
156
    Deprecated: use WorkingTree.open_containing_paths instead.
157
1658.1.8 by Martin Pool
(internal_tree_files) Better docstring
158
    This is typically used for command-line processors that take one or
159
    more filenames, and infer the workingtree that contains them.
160
161
    The filenames given are not required to exist.
162
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
163
    :param file_list: Filenames to convert.
1658.1.8 by Martin Pool
(internal_tree_files) Better docstring
164
2091.3.2 by Aaron Bentley
Traverse non-terminal symlinks for mv et al
165
    :param default_branch: Fallback tree path to use if file_list is empty or
166
        None.
1658.1.8 by Martin Pool
(internal_tree_files) Better docstring
167
3586.1.9 by Ian Clatworthy
first cut at view command
168
    :param apply_view: if True and a view is set, apply it or check that
169
        specified files are within it
170
1658.1.8 by Martin Pool
(internal_tree_files) Better docstring
171
    :return: workingtree, [relative_paths]
1185.12.101 by Aaron Bentley
Made commit take branch from first argument, if supplied.
172
    """
5346.4.2 by Martin Pool
Move internal_tree_files and safe_relpath_files onto WorkingTree
173
    return WorkingTree.open_containing_paths(
174
        file_list, default_directory='.',
175
        canonicalize=True,
176
        apply_view=True)
1553.5.78 by Martin Pool
New bzr init --format option and test
177
178
3586.1.31 by Ian Clatworthy
view filtering for pull, update & merge
179
def _get_view_info_for_change_reporter(tree):
180
    """Get the view information from a tree for change reporting."""
181
    view_info = None
182
    try:
183
        current_view = tree.views.get_view_info()[0]
184
        if current_view is not None:
185
            view_info = (current_view, tree.views.lookup_view())
186
    except errors.ViewsNotSupported:
187
        pass
188
    return view_info
189
190
5171.3.9 by Martin von Gagern
Rename function to _open_directory_or_containing_tree_or_branch.
191
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.
192
    """Open the tree or branch containing the specified file, unless
193
    the --directory option is used to specify a different branch."""
194
    if directory is not None:
195
        return (None, Branch.open(directory), filename)
196
    return bzrdir.BzrDir.open_containing_tree_or_branch(filename)
197
198
1185.16.112 by mbp at sourcefrog
todo
199
# TODO: Make sure no commands unconditionally use the working directory as a
200
# branch.  If a filename argument is used, the first of them should be used to
201
# specify the branch.  (Perhaps this can be factored out into some kind of
202
# Argument class, representing a file in a branch, where the first occurrence
203
# opens the branch?)
204
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
205
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
206
    __doc__ = """Display status summary.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
207
208
    This reports on versioned and unknown files, reporting them
209
    grouped by state.  Possible states are:
210
1551.10.10 by Aaron Bentley
Add help text
211
    added
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
212
        Versioned in the working copy but not in the previous revision.
213
1551.10.10 by Aaron Bentley
Add help text
214
    removed
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
215
        Versioned in the previous revision but removed or deleted
216
        in the working copy.
217
1551.10.10 by Aaron Bentley
Add help text
218
    renamed
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
219
        Path of this file changed from the previous revision;
220
        the text may also have changed.  This includes files whose
221
        parent directory was renamed.
222
1551.10.10 by Aaron Bentley
Add help text
223
    modified
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
224
        Text has changed since the previous revision.
225
1551.10.10 by Aaron Bentley
Add help text
226
    kind changed
227
        File kind has been changed (e.g. from file to directory).
228
229
    unknown
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
230
        Not versioned and not matching an ignore pattern.
231
4798.5.2 by Neil Martinsen-Burrell
Put discussion of type indicators in the appropriate place under status
232
    Additionally for directories, symlinks and files with an executable
233
    bit, Bazaar indicates their type using a trailing character: '/', '@'
234
    or '*' respectively.
235
2374.1.1 by Ian Clatworthy
Help and man page fixes
236
    To see ignored files use 'bzr ignored'.  For details on the
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
237
    changes to file texts, use 'bzr diff'.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
238
2792.1.1 by Ian Clatworthy
Add short options to status to assist migrating svn users (Daniel Watkins)
239
    Note that --short or -S gives status flags for each item, similar
240
    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
241
    use bzr status -SV.
1551.10.10 by Aaron Bentley
Add help text
242
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
243
    If no arguments are specified, the status of the entire working
244
    directory is shown.  Otherwise, only the status of the specified
245
    files or directories is reported.  If a directory is given, status
246
    is reported for everything inside that directory.
1185.1.35 by Robert Collins
Heikki Paajanen's status -r patch
247
3936.2.2 by Ian Clatworthy
add NEWS item & improve status help
248
    Before merges are committed, the pending merge tip revisions are
249
    shown. To see all pending merge revisions, use the -v option.
250
    To skip the display of pending merge information altogether, use
251
    the no-pending option or specify a file/directory.
252
1185.1.35 by Robert Collins
Heikki Paajanen's status -r patch
253
    If a revision argument is given, the status is calculated against
254
    that revision, or between two revisions if two are provided.
1185.3.2 by Martin Pool
- remove -r option from status command because it's not used
255
    """
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
256
1185.16.76 by Martin Pool
doc
257
    # TODO: --no-recurse, --recurse options
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
258
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
259
    takes_args = ['file*']
3936.2.1 by Ian Clatworthy
verbose flag for status - code & tests
260
    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)
261
                     Option('short', help='Use short status indicators.',
2663.1.7 by Daniel Watkins
Capitalised short names.
262
                            short_name='S'),
2663.1.5 by Daniel Watkins
Changed 'bzr stat --quiet' to 'bzr stat -(vs|sv)', as per list suggestions.
263
                     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)
264
                            short_name='V'),
265
                     Option('no-pending', help='Don\'t show pending merges.',
266
                           ),
2663.1.5 by Daniel Watkins
Changed 'bzr stat --quiet' to 'bzr stat -(vs|sv)', as per list suggestions.
267
                     ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
268
    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()
269
270
    encoding_type = 'replace'
2520.1.3 by Daniel Watkins
'help status' now points to 'help status-flags'.
271
    _see_also = ['diff', 'revert', 'status-flags']
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
272
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
273
    @display_command
2318.2.1 by Kent Gibson
Apply status versioned patch
274
    def run(self, show_ids=False, file_list=None, revision=None, short=False,
3936.2.1 by Ian Clatworthy
verbose flag for status - code & tests
275
            versioned=False, no_pending=False, verbose=False):
1551.2.9 by Aaron Bentley
Fix status to work with checkouts
276
        from bzrlib.status import show_tree_status
1185.85.15 by John Arbash Meinel
Updated bzr status, adding test_cat
277
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.
278
        if revision and len(revision) > 2:
279
            raise errors.BzrCommandError('bzr status --revision takes exactly'
280
                                         ' 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)
281
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
282
        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
283
        # Avoid asking for specific files when that is not needed.
284
        if relfile_list == ['']:
285
            relfile_list = None
286
            # Don't disable pending merges for full trees other than '.'.
287
            if file_list == ['.']:
288
                no_pending = True
289
        # A specific path within a tree was given.
290
        elif relfile_list is not None:
291
            no_pending = True
1773.1.2 by Robert Collins
Remove --all option from status.
292
        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
293
                         specific_files=relfile_list, revision=revision,
3270.6.1 by James Westby
Add --no-pending to status to not show the pending merges. (#202830)
294
                         to_file=self.outf, short=short, versioned=versioned,
3936.2.1 by Ian Clatworthy
verbose flag for status - code & tests
295
                         show_pending=(not no_pending), verbose=verbose)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
296
297
298
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
299
    __doc__ = """Write out metadata for a revision.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
300
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
301
    The revision to print can either be specified by a specific
302
    revision identifier, or you can use --revision.
303
    """
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
304
305
    hidden = True
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
306
    takes_args = ['revision_id?']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
307
    takes_options = ['directory', 'revision']
1685.1.76 by Wouter van Heyst
codecleanup
308
    # cat-revision is more for frontends so should be exact
309
    encoding = 'strict'
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
310
5035.2.1 by Jelmer Vernooij
Repository.get_revision_xml() has been removed.
311
    def print_revision(self, revisions, revid):
312
        stream = revisions.get_record_stream([(revid,)], 'unordered', True)
313
        record = stream.next()
314
        if record.storage_kind == 'absent':
315
            raise errors.NoSuchRevision(revisions, revid)
316
        revtext = record.get_bytes_as('fulltext')
317
        self.outf.write(revtext.decode('utf-8'))
318
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
319
    @display_command
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
320
    def run(self, revision_id=None, revision=None, directory=u'.'):
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
321
        if revision_id is not None and revision is not None:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
322
            raise errors.BzrCommandError('You can only supply one of'
323
                                         ' revision_id or --revision')
1185.5.3 by John Arbash Meinel
cat-revision allows --revision for easier investigation.
324
        if revision_id is None and revision is None:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
325
            raise errors.BzrCommandError('You must supply either'
326
                                         ' --revision or a revision_id')
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
327
        b = WorkingTree.open_containing(directory)[0].branch
1185.85.72 by John Arbash Meinel
Fix some of the tests.
328
5035.2.1 by Jelmer Vernooij
Repository.get_revision_xml() has been removed.
329
        revisions = b.repository.revisions
330
        if revisions is None:
331
            raise errors.BzrCommandError('Repository %r does not support '
332
                'access to raw revision texts')
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
333
5035.2.1 by Jelmer Vernooij
Repository.get_revision_xml() has been removed.
334
        b.repository.lock_read()
335
        try:
336
            # TODO: jam 20060112 should cat-revision always output utf-8?
337
            if revision_id is not None:
338
                revision_id = osutils.safe_revision_id(revision_id, warn=False)
339
                try:
340
                    self.print_revision(revisions, revision_id)
341
                except errors.NoSuchRevision:
342
                    msg = "The repository %s contains no revision %s." % (
343
                        b.repository.base, revision_id)
344
                    raise errors.BzrCommandError(msg)
345
            elif revision is not None:
346
                for rev in revision:
347
                    if rev is None:
348
                        raise errors.BzrCommandError(
349
                            'You cannot specify a NULL revision.')
350
                    rev_id = rev.as_revision_id(b)
351
                    self.print_revision(revisions, rev_id)
352
        finally:
353
            b.repository.unlock()
354
        
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
355
356
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
357
    __doc__ = """Dump the contents of a btree index file to stdout.
3770.1.4 by John Arbash Meinel
Clarify the help text a bit.
358
359
    PATH is a btree index file, it can be any URL. This includes things like
360
    .bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
361
362
    By default, the tuples stored in the index file will be displayed. With
363
    --raw, we will uncompress the pages, but otherwise display the raw bytes
364
    stored in the index.
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
365
    """
366
367
    # TODO: Do we want to dump the internal nodes as well?
368
    # TODO: It would be nice to be able to dump the un-parsed information,
369
    #       rather than only going through iter_all_entries. However, this is
370
    #       good enough for a start
371
    hidden = True
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
372
    encoding_type = 'exact'
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
373
    takes_args = ['path']
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
374
    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'
375
                                        ' rather than the parsed tuples.'),
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
376
                    ]
377
378
    def run(self, path, raw=False):
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
379
        dirname, basename = osutils.split(path)
380
        t = transport.get_transport(dirname)
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
381
        if raw:
382
            self._dump_raw_bytes(t, basename)
383
        else:
384
            self._dump_entries(t, basename)
385
386
    def _get_index_and_bytes(self, trans, basename):
387
        """Create a BTreeGraphIndex and raw bytes."""
388
        bt = btree_index.BTreeGraphIndex(trans, basename, None)
389
        bytes = trans.get_bytes(basename)
390
        bt._file = cStringIO.StringIO(bytes)
391
        bt._size = len(bytes)
392
        return bt, bytes
393
394
    def _dump_raw_bytes(self, trans, basename):
395
        import zlib
396
397
        # We need to parse at least the root node.
398
        # This is because the first page of every row starts with an
399
        # uncompressed header.
400
        bt, bytes = self._get_index_and_bytes(trans, basename)
3770.1.3 by John Arbash Meinel
Simplify the --raw mode.
401
        for page_idx, page_start in enumerate(xrange(0, len(bytes),
402
                                                     btree_index._PAGE_SIZE)):
403
            page_end = min(page_start + btree_index._PAGE_SIZE, len(bytes))
404
            page_bytes = bytes[page_start:page_end]
405
            if page_idx == 0:
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
406
                self.outf.write('Root node:\n')
3770.1.3 by John Arbash Meinel
Simplify the --raw mode.
407
                header_end, data = bt._parse_header_from_bytes(page_bytes)
408
                self.outf.write(page_bytes[:header_end])
409
                page_bytes = data
410
            self.outf.write('\nPage %d\n' % (page_idx,))
411
            decomp_bytes = zlib.decompress(page_bytes)
412
            self.outf.write(decomp_bytes)
413
            self.outf.write('\n')
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
414
415
    def _dump_entries(self, trans, basename):
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
416
        try:
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
417
            st = trans.stat(basename)
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
418
        except errors.TransportNotPossible:
419
            # We can't stat, so we'll fake it because we have to do the 'get()'
420
            # anyway.
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
421
            bt, _ = self._get_index_and_bytes(trans, basename)
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
422
        else:
3770.1.2 by John Arbash Meinel
Add a --raw output for dump-btree.
423
            bt = btree_index.BTreeGraphIndex(trans, basename, st.st_size)
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
424
        for node in bt.iter_all_entries():
425
            # Node is made up of:
426
            # (index, key, value, [references])
5091.1.1 by Andrew Bennetts
Fix dump-btree to handle *.cix and *.six files.
427
            try:
428
                refs = node[3]
429
            except IndexError:
430
                refs_as_tuples = None
431
            else:
432
                refs_as_tuples = static_tuple.as_tuples(refs)
4679.8.9 by John Arbash Meinel
Cast objects back to tuples for 'dump-btree'
433
            as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
434
            self.outf.write('%s\n' % (as_tuple,))
3770.1.1 by John Arbash Meinel
First draft of a basic dump-btree command.
435
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
436
2127.2.1 by Daniel Silverstone
Add remove-tree and its blackbox tests
437
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
438
    __doc__ = """Remove the working tree from a given branch/checkout.
2127.2.1 by Daniel Silverstone
Add remove-tree and its blackbox tests
439
440
    Since a lightweight checkout is little more than a working tree
441
    this will refuse to run against one.
2374.1.3 by Ian Clatworthy
Minor man page fixes for add, commit, export
442
2374.1.4 by Ian Clatworthy
Include feedback from mailing list.
443
    To re-create the working tree, use "bzr checkout".
2127.2.1 by Daniel Silverstone
Add remove-tree and its blackbox tests
444
    """
2485.1.2 by James Westby
Update with comments from review, thanks to John and Aaron.
445
    _see_also = ['checkout', 'working-trees']
4748.1.1 by Jared Hance
Fixed bug by changing location to a list and iterating through list.
446
    takes_args = ['location*']
3667.2.1 by Lukáš Lalinský
Make `bzr remove-tree` not remove trees with uncommitted changes by default
447
    takes_options = [
448
        Option('force',
449
               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.
450
                    'uncommitted or shelved changes.'),
3667.2.1 by Lukáš Lalinský
Make `bzr remove-tree` not remove trees with uncommitted changes by default
451
        ]
2127.2.1 by Daniel Silverstone
Add remove-tree and its blackbox tests
452
4748.1.1 by Jared Hance
Fixed bug by changing location to a list and iterating through list.
453
    def run(self, location_list, force=False):
454
        if not location_list:
455
            location_list=['.']
456
457
        for location in location_list:
458
            d = bzrdir.BzrDir.open(location)
459
            
460
            try:
461
                working = d.open_workingtree()
462
            except errors.NoWorkingTree:
463
                raise errors.BzrCommandError("No working tree to remove")
464
            except errors.NotLocalUrl:
465
                raise errors.BzrCommandError("You cannot remove the working tree"
466
                                             " of a remote path")
467
            if not force:
468
                if (working.has_changes()):
469
                    raise errors.UncommittedChanges(working)
5268.3.1 by Matt Giuca
remove-tree now refuses to run without --force if there are shelved changes.
470
                if working.get_shelf_manager().last_shelf() is not None:
471
                    raise errors.ShelvedChanges(working)
4748.1.1 by Jared Hance
Fixed bug by changing location to a list and iterating through list.
472
5158.6.9 by Martin Pool
Simplify various code to use user_url
473
            if working.user_url != working.branch.user_url:
4748.1.9 by Andrew Bennetts
Fix bug introduced by the change to take multiple locations, and add a test for multiple locations.
474
                raise errors.BzrCommandError("You cannot remove the working tree"
475
                                             " from a lightweight checkout")
4748.1.1 by Jared Hance
Fixed bug by changing location to a list and iterating through list.
476
4748.1.9 by Andrew Bennetts
Fix bug introduced by the change to take multiple locations, and add a test for multiple locations.
477
            d.destroy_workingtree()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
478
2127.2.1 by Daniel Silverstone
Add remove-tree and its blackbox tests
479
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
480
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
481
    __doc__ = """Show current revision number.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
482
1185.85.24 by John Arbash Meinel
Moved run_bzr_decode into TestCase
483
    This is equal to the number of revisions on this branch.
484
    """
485
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
486
    _see_also = ['info']
1185.50.16 by John Arbash Meinel
[patch] Michael Ellerman: 'Trivial patch to allow revno to take a location'
487
    takes_args = ['location?']
4409.1.1 by Matthew Fuller
Add a --tree option to revno.
488
    takes_options = [
489
        Option('tree', help='Show revno of working tree'),
490
        ]
1185.85.24 by John Arbash Meinel
Moved run_bzr_decode into TestCase
491
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
492
    @display_command
4409.1.1 by Matthew Fuller
Add a --tree option to revno.
493
    def run(self, tree=False, location=u'.'):
4409.1.21 by Vincent Ladeuil
Fix failing test.
494
        if tree:
495
            try:
496
                wt = WorkingTree.open_containing(location)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
497
                self.add_cleanup(wt.lock_read().unlock)
4409.1.21 by Vincent Ladeuil
Fix failing test.
498
            except (errors.NoWorkingTree, errors.NotLocalUrl):
499
                raise errors.NoWorkingTree(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.
500
            revid = wt.last_revision()
4409.1.21 by Vincent Ladeuil
Fix failing test.
501
            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.
502
                revno_t = wt.branch.revision_id_to_dotted_revno(revid)
503
            except errors.NoSuchRevision:
504
                revno_t = ('???',)
505
            revno = ".".join(str(n) for n in revno_t)
4409.1.21 by Vincent Ladeuil
Fix failing test.
506
        else:
507
            b = Branch.open_containing(location)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
508
            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.
509
            revno = b.revno()
510
        self.cleanup_now()
4409.1.1 by Matthew Fuller
Add a --tree option to revno.
511
        self.outf.write(str(revno) + '\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
512
1182 by Martin Pool
- more disentangling of xml storage format from objects
513
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
514
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
515
    __doc__ = """Show revision number and revision id for a given revision identifier.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
516
    """
517
    hidden = True
518
    takes_args = ['revision_info*']
3886.1.1 by Michael Hudson
support -d in the revision-info command
519
    takes_options = [
520
        'revision',
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
521
        custom_help('directory',
3886.1.1 by Michael Hudson
support -d in the revision-info command
522
            help='Branch to examine, '
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
523
                 'rather than the one containing the working directory.'),
4409.1.3 by Matthew Fuller
Add --tree option to revision-info too.
524
        Option('tree', help='Show revno of working tree'),
3886.1.1 by Michael Hudson
support -d in the revision-info command
525
        ]
1185.85.24 by John Arbash Meinel
Moved run_bzr_decode into TestCase
526
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
527
    @display_command
4409.1.3 by Matthew Fuller
Add --tree option to revision-info too.
528
    def run(self, revision=None, directory=u'.', tree=False,
529
            revision_info_list=[]):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
530
4409.1.10 by John Arbash Meinel
Clean up 'bzr revision-info' to support revision not in the branch history.
531
        try:
532
            wt = WorkingTree.open_containing(directory)[0]
533
            b = wt.branch
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
534
            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.
535
        except (errors.NoWorkingTree, errors.NotLocalUrl):
536
            wt = None
537
            b = Branch.open_containing(directory)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
538
            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.
539
        revision_ids = []
540
        if revision is not None:
541
            revision_ids.extend(rev.as_revision_id(b) for rev in revision)
542
        if revision_info_list is not None:
543
            for rev_str in revision_info_list:
544
                rev_spec = RevisionSpec.from_string(rev_str)
545
                revision_ids.append(rev_spec.as_revision_id(b))
546
        # No arguments supplied, default to the last revision
547
        if len(revision_ids) == 0:
548
            if tree:
549
                if wt is None:
550
                    raise errors.NoWorkingTree(directory)
551
                revision_ids.append(wt.last_revision())
4409.1.3 by Matthew Fuller
Add --tree option to revision-info too.
552
            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.
553
                revision_ids.append(b.last_revision())
554
555
        revinfos = []
556
        maxlen = 0
557
        for revision_id in revision_ids:
558
            try:
559
                dotted_revno = b.revision_id_to_dotted_revno(revision_id)
560
                revno = '.'.join(str(i) for i in dotted_revno)
561
            except errors.NoSuchRevision:
562
                revno = '???'
563
            maxlen = max(maxlen, len(revno))
564
            revinfos.append([revno, revision_id])
565
566
        self.cleanup_now()
4409.2.1 by Matthew Fuller
Rework revision-info command so that it:
567
        for ri in revinfos:
4409.1.17 by Matthew Fuller
Merge in revision-info cleanups and changes.
568
            self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
569
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
570
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
571
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
572
    __doc__ = """Add specified files or directories.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
573
574
    In non-recursive mode, all the named items are added, regardless
575
    of whether they were previously ignored.  A warning is given if
576
    any of the named files are already versioned.
577
578
    In recursive mode (the default), files are treated the same way
579
    but the behaviour for directories is different.  Directories that
580
    are already versioned do not give a warning.  All directories,
581
    whether already versioned or not, are searched for files or
582
    subdirectories that are neither versioned or ignored, and these
583
    are added.  This search proceeds recursively into versioned
584
    directories.  If no names are given '.' is assumed.
585
586
    Therefore simply saying 'bzr add' will version all files that
587
    are currently unknown.
588
1185.3.3 by Martin Pool
- patch from mpe to automatically add parent directories
589
    Adding a file whose parent directory is not versioned will
590
    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).
591
    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
592
    get added when you add a file in the directory.
1185.33.90 by Martin Pool
[merge] add --dry-run option (mpe)
593
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
594
    --dry-run will show which files would be added, but not actually
1185.33.90 by Martin Pool
[merge] add --dry-run option (mpe)
595
    add them.
1911.3.2 by John Arbash Meinel
Adding the AddFromBaseAction, which tries to reuse file ids from another tree
596
597
    --file-ids-from will try to use the file ids from the supplied path.
598
    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
599
    same filename, and then by pure path. This option is rarely needed
600
    but can be useful when adding the same logical file into two
601
    branches that will be merged later (without showing the two different
2374.1.4 by Ian Clatworthy
Include feedback from mailing list.
602
    adds as a conflict). It is also useful when merging another project
603
    into a subdirectory of this one.
4595.1.1 by Jason Spashett
Further tweaks to bzr add
604
    
4595.1.2 by Martin Pool
typo
605
    Any files matching patterns in the ignore list will not be added
4595.1.1 by Jason Spashett
Further tweaks to bzr add
606
    unless they are explicitly mentioned.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
607
    """
608
    takes_args = ['file*']
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
609
    takes_options = [
610
        Option('no-recurse',
2598.1.11 by Martin Pool
Insist that all options have a help string and fix those that don't.
611
               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.
612
        Option('dry-run',
613
               help="Show what would be done, but don't actually do anything."),
614
        'verbose',
615
        Option('file-ids-from',
616
               type=unicode,
617
               help='Lookup file ids from this tree.'),
618
        ]
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
619
    encoding_type = 'replace'
4595.1.1 by Jason Spashett
Further tweaks to bzr add
620
    _see_also = ['remove', 'ignore']
1185.53.1 by Michael Ellerman
Add support for bzr add --dry-run
621
1911.3.2 by John Arbash Meinel
Adding the AddFromBaseAction, which tries to reuse file ids from another tree
622
    def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
623
            file_ids_from=None):
1185.53.1 by Michael Ellerman
Add support for bzr add --dry-run
624
        import bzrlib.add
625
2255.7.69 by Robert Collins
Fix all blackbox add tests, and the add --from-ids case in the UI.
626
        base_tree = None
1911.3.2 by John Arbash Meinel
Adding the AddFromBaseAction, which tries to reuse file ids from another tree
627
        if file_ids_from is not None:
628
            try:
629
                base_tree, base_path = WorkingTree.open_containing(
630
                                            file_ids_from)
631
            except errors.NoWorkingTree:
1996.3.1 by John Arbash Meinel
Demandloading builtins.py drops our load time from 350ms to 291ms
632
                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
633
                                            file_ids_from)
634
                base_tree = base_branch.basis_tree()
635
636
            action = bzrlib.add.AddFromBaseAction(base_tree, base_path,
637
                          to_file=self.outf, should_print=(not is_quiet()))
638
        else:
639
            action = bzrlib.add.AddAction(to_file=self.outf,
640
                should_print=(not is_quiet()))
641
2255.7.69 by Robert Collins
Fix all blackbox add tests, and the add --from-ids case in the UI.
642
        if base_tree:
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
643
            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.
644
        tree, file_list = tree_files_for_add(file_list)
645
        added, ignored = tree.smart_add(file_list, not
646
            no_recurse, action=action, save=not dry_run)
647
        self.cleanup_now()
1185.46.8 by Aaron Bentley
bzr add reports ignored patterns.
648
        if len(ignored) > 0:
1711.1.2 by Robert Collins
'bzr add' is now less verbose in telling you what ignore globs were
649
            if verbose:
650
                for glob in sorted(ignored.keys()):
1185.46.9 by Aaron Bentley
Added verbose option to bzr add, to list all ignored files.
651
                    for path in ignored[glob]:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
652
                        self.outf.write("ignored %s matching \"%s\"\n"
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()
653
                                        % (path, glob))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
654
655
656
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
657
    __doc__ = """Create a new versioned directory.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
658
659
    This is equivalent to creating the directory and then adding it.
660
    """
1685.1.80 by Wouter van Heyst
more code cleanup
661
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
662
    takes_args = ['dir+']
1185.85.22 by John Arbash Meinel
Updated cmd_inventory. Changing from having each Command request an encoded stdout to providing one before calling run()
663
    encoding_type = 'replace'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
664
665
    def run(self, dir_list):
666
        for d in dir_list:
5036.2.1 by Parth Malwankar
fix 138600. `bzr mkdir` create new dir before it checks
667
            wt, dd = WorkingTree.open_containing(d)
5036.2.4 by Parth Malwankar
test cases running and passing
668
            base = os.path.dirname(dd)
5036.2.7 by Parth Malwankar
fixed mkdir and added test case for unversioned dir within branch
669
            id = wt.path2id(base)
670
            if id != None:
671
                os.mkdir(d)
672
                wt.add([dd])
673
                self.outf.write('added %s\n' % d)
674
            else:
675
                raise errors.NotVersionedError(path=base)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
676
677
678
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
679
    __doc__ = """Show path of a file relative to root"""
1685.1.80 by Wouter van Heyst
more code cleanup
680
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
681
    takes_args = ['filename']
682
    hidden = True
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
683
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
684
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
685
    def run(self, filename):
1185.85.19 by John Arbash Meinel
Updated bzr relpath
686
        # TODO: jam 20050106 Can relpath return a munged path if
687
        #       sys.stdout encoding cannot represent it?
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
688
        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()
689
        self.outf.write(relpath)
690
        self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
691
692
693
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
694
    __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'
695
696
    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'
697
    type using the --kind option.  For example: --kind file.
698
699
    It is also possible to restrict the list of files to a specific
700
    set. For example: bzr inventory --show-ids this/file
1185.33.33 by Martin Pool
[patch] add 'bzr inventory --kind directory'; remove 'bzr directories'
701
    """
1685.1.80 by Wouter van Heyst
more code cleanup
702
1551.10.13 by Aaron Bentley
Hide 'unknowns', document alterntatives to hidden commands
703
    hidden = True
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
704
    _see_also = ['ls']
2598.1.11 by Martin Pool
Insist that all options have a help string and fix those that don't.
705
    takes_options = [
706
        'revision',
707
        'show-ids',
708
        Option('kind',
2598.1.12 by Martin Pool
Fix up --kind options
709
               help='List entries of a particular kind: file, directory, symlink.',
710
               type=unicode),
2598.1.11 by Martin Pool
Insist that all options have a help string and fix those that don't.
711
        ]
2027.4.2 by John Arbash Meinel
Fix bug #3631, allow 'bzr inventory filename'
712
    takes_args = ['file*']
713
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
714
    @display_command
2027.4.2 by John Arbash Meinel
Fix bug #3631, allow 'bzr inventory filename'
715
    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'
716
        if kind and kind not in ['file', 'directory', 'symlink']:
2598.1.12 by Martin Pool
Fix up --kind options
717
            raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
2027.4.3 by John Arbash Meinel
Change how 'bzr inventory' finds paths
718
3984.3.7 by Daniel Watkins
Fixed incorrect calls.
719
        revision = _get_one_revision('inventory', revision)
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
720
        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
721
        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.
722
        if revision is not None:
723
            tree = revision.as_tree(work_tree.branch)
724
725
            extra_trees = [work_tree]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
726
            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.
727
        else:
728
            tree = work_tree
729
            extra_trees = []
730
731
        if file_list is not None:
732
            file_ids = tree.paths2ids(file_list, trees=extra_trees,
733
                                      require_versioned=True)
734
            # find_ids_across_trees may include some paths that don't
735
            # exist in 'tree'.
736
            entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
737
                             for file_id in file_ids if file_id in tree)
738
        else:
739
            entries = tree.inventory.entries()
740
741
        self.cleanup_now()
2027.4.2 by John Arbash Meinel
Fix bug #3631, allow 'bzr inventory filename'
742
        for path, entry in entries:
1185.33.33 by Martin Pool
[patch] add 'bzr inventory --kind directory'; remove 'bzr directories'
743
            if kind and kind != entry.kind:
744
                continue
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
745
            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()
746
                self.outf.write('%-50s %s\n' % (path, entry.file_id))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
747
            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()
748
                self.outf.write(path)
749
                self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
750
751
752
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
753
    __doc__ = """Move or rename a file.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
754
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
755
    :Usage:
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
756
        bzr mv OLDNAME NEWNAME
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
757
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
758
        bzr mv SOURCE... DESTINATION
759
760
    If the last argument is a versioned directory, all the other names
761
    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
762
    and the file is changed to a new name.
763
764
    If OLDNAME does not exist on the filesystem but is versioned and
765
    NEWNAME does exist on the filesystem but is not versioned, mv
766
    assumes that the file has been manually moved and only updates
767
    its internal inventory to reflect that change.
768
    The same is valid when moving many SOURCE files to a DESTINATION.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
769
770
    Files cannot be moved between branches.
771
    """
1685.1.80 by Wouter van Heyst
more code cleanup
772
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
773
    takes_args = ['names*']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
774
    takes_options = [Option("after", help="Move only the bzr identifier"
775
        " of the file, because the file has already been moved."),
3193.8.37 by Aaron Bentley
Finish up conversion to mv --auto.
776
        Option('auto', help='Automatically guess renames.'),
777
        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
778
        ]
1616.1.8 by Martin Pool
Unify 'mv', 'move', 'rename'. (#5379, Matthew Fuller)
779
    aliases = ['move', 'rename']
1185.85.26 by John Arbash Meinel
bzr mv should succeed even if it can't display the paths.
780
    encoding_type = 'replace'
781
3193.8.37 by Aaron Bentley
Finish up conversion to mv --auto.
782
    def run(self, names_list, after=False, auto=False, dry_run=False):
3193.8.35 by Aaron Bentley
Implement mv --auto.
783
        if auto:
3193.8.37 by Aaron Bentley
Finish up conversion to mv --auto.
784
            return self.run_auto(names_list, after, dry_run)
785
        elif dry_run:
786
            raise errors.BzrCommandError('--dry-run requires --auto.')
1846.1.1 by Wouter van Heyst
Don't fail on 'bzr mv', extract move tests from OldTests.
787
        if names_list is None:
788
            names_list = []
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
789
        if len(names_list) < 2:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
790
            raise errors.BzrCommandError("missing file argument")
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
791
        tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
792
        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.
793
        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.
794
3193.8.37 by Aaron Bentley
Finish up conversion to mv --auto.
795
    def run_auto(self, names_list, after, dry_run):
3193.8.36 by Aaron Bentley
Get remaining behaviour under test.
796
        if names_list is not None and len(names_list) > 1:
797
            raise errors.BzrCommandError('Only one path may be specified to'
798
                                         ' --auto.')
3193.8.37 by Aaron Bentley
Finish up conversion to mv --auto.
799
        if after:
800
            raise errors.BzrCommandError('--after cannot be specified with'
801
                                         ' --auto.')
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
802
        work_tree, file_list = WorkingTree.open_containing_paths(
5346.4.6 by Martin Pool
Update parameter name
803
            names_list, default_directory='.')
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
804
        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.
805
        rename_map.RenameMap.guess_renames(work_tree, dry_run)
3193.8.35 by Aaron Bentley
Implement mv --auto.
806
3201.2.1 by Lukáš Lalinský
Make 'mv a b' work for already renamed directories, like it does for files
807
    def _run(self, tree, names_list, rel_names, after):
808
        into_existing = osutils.isdir(names_list[-1])
809
        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.
810
            # special cases:
811
            # a. case-insensitive filesystem and change case of dir
812
            # b. move directory after the fact (if the source used to be
813
            #    a directory, but now doesn't exist in the working tree
814
            #    and the target is an existing directory, just rename it)
815
            if (not tree.case_sensitive
816
                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
817
                into_existing = False
3249.4.1 by Alexander Belchenko
merge Lukas' patch and update it with case-insensitive rename check.
818
            else:
819
                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.
820
                # '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'
821
                from_id = tree.path2id(
822
                            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.
823
                if (not osutils.lexists(names_list[0]) and
824
                    from_id and inv.get_file_kind(from_id) == "directory"):
825
                    into_existing = False
826
        # move/rename
3201.2.1 by Lukáš Lalinský
Make 'mv a b' work for already renamed directories, like it does for files
827
        if into_existing:
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
828
            # 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.
829
            # All entries reference existing inventory items, so fix them up
830
            # 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'
831
            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.
832
            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.
833
                if not is_quiet():
834
                    self.outf.write("%s => %s\n" % (src, dest))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
835
        else:
836
            if len(names_list) != 2:
2123.3.1 by Steffen Eichenberg
the mv command is now able to move files that have already been moved on the file system
837
                raise errors.BzrCommandError('to mv multiple files the'
838
                                             ' destination must be a versioned'
839
                                             ' 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.
840
841
            # for cicp file-systems: the src references an existing inventory
842
            # item:
3794.5.20 by Mark Hammond
Use get_canonical_inventory_path and get_canonical_inventory_paths, and handle more edge cases in 'mv'
843
            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.
844
            # Find the canonical version of the destination:  In all cases, the
845
            # 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'
846
            # canonical version from there (we do not always *use* the
847
            # canonicalized tail portion - we may be attempting to rename the
848
            # case of the tail)
849
            canon_dest = tree.get_canonical_inventory_path(rel_names[1])
850
            dest_parent = osutils.dirname(canon_dest)
851
            spec_tail = osutils.basename(rel_names[1])
852
            # For a CICP file-system, we need to avoid creating 2 inventory
853
            # entries that differ only by case.  So regardless of the case
854
            # we *want* to use (ie, specified by the user or the file-system),
855
            # we must always choose to use the case of any existing inventory
856
            # items.  The only exception to this is when we are attempting a
857
            # case-only rename (ie, canonical versions of src and dest are
858
            # the same)
859
            dest_id = tree.path2id(canon_dest)
860
            if dest_id is None or tree.path2id(src) == dest_id:
861
                # No existing item we care about, so work out what case we
862
                # are actually going to use.
863
                if after:
864
                    # If 'after' is specified, the tail must refer to a file on disk.
865
                    if dest_parent:
866
                        dest_parent_fq = osutils.pathjoin(tree.basedir, dest_parent)
867
                    else:
868
                        # pathjoin with an empty tail adds a slash, which breaks
869
                        # relpath :(
870
                        dest_parent_fq = tree.basedir
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
871
3794.5.20 by Mark Hammond
Use get_canonical_inventory_path and get_canonical_inventory_paths, and handle more edge cases in 'mv'
872
                    dest_tail = osutils.canonical_relpath(
873
                                    dest_parent_fq,
874
                                    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.
875
                else:
3794.5.20 by Mark Hammond
Use get_canonical_inventory_path and get_canonical_inventory_paths, and handle more edge cases in 'mv'
876
                    # not 'after', so case as specified is used
877
                    dest_tail = spec_tail
878
            else:
879
                # Use the existing item so 'mv' fails with AlreadyVersioned.
880
                dest_tail = os.path.basename(canon_dest)
3794.5.11 by Mark Hammond
whitespace/logging changes.
881
            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'
882
            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.
883
            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.
884
            if not is_quiet():
885
                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.
886
887
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
888
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
889
    __doc__ = """Turn this branch into a mirror of another branch.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
890
4840.1.1 by Patrick Regan
Added extra clarification to pull cmd.
891
    By default, this command only works on branches that have not diverged.
892
    Branches are considered diverged if the destination branch's most recent 
893
    commit is one that has not been merged (directly or indirectly) into the 
894
    parent.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
895
1661.1.1 by Martin Pool
[merge] olaf's --remember changes
896
    If branches have diverged, you can use 'bzr merge' to integrate the changes
897
    from one into the other.  Once one branch has merged, the other should
898
    be able to pull it again.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
899
4840.1.1 by Patrick Regan
Added extra clarification to pull cmd.
900
    If you want to replace your local changes and just want your branch to
901
    match the remote one, use pull --overwrite. This will work even if the two
902
    branches have diverged.
1614.2.3 by Olaf Conradi
In commands push and pull, moved help text for --remember down. It's not
903
904
    If there is no default location set, the first pull will set it.  After
905
    that, you can omit the location to use the default.  To change the
1785.1.4 by John Arbash Meinel
Update help for the new --remember semantics.
906
    default, use --remember. The value will only be saved if the remote
907
    location can be accessed.
3313.1.1 by Ian Clatworthy
Improve doc on send/merge relationship (Peter Schuller)
908
909
    Note: The location can be specified either in the form of a branch,
910
    or in the form of a path to a file containing a merge directive generated
911
    with bzr send.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
912
    """
1685.1.80 by Wouter van Heyst
more code cleanup
913
4095.2.1 by Neil Martinsen-Burrell
Better help for bzr send
914
    _see_also = ['push', 'update', 'status-flags', 'send']
1551.17.4 by Aaron Bentley
Make pull -v description more specific
915
    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
916
        custom_help('verbose',
1551.17.4 by Aaron Bentley
Make pull -v description more specific
917
            help='Show logs of pulled revisions.'),
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
918
        custom_help('directory',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
919
            help='Branch to pull into, '
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
920
                 'rather than the one containing the working directory.'),
4056.6.1 by Gary van der Merwe
Add --local option to pull.
921
        Option('local',
922
            help="Perform a local pull in a bound "
923
                 "branch.  Local pulls are not applied to "
924
                 "the master branch."
925
            ),
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
926
        ]
2520.1.6 by Daniel Watkins
Fixed 'pull' help.
927
    takes_args = ['location?']
1185.85.27 by John Arbash Meinel
Updated bzr branch and bzr pull
928
    encoding_type = 'replace'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
929
1551.11.10 by Aaron Bentley
Add change reporting to pull
930
    def run(self, location=None, remember=False, overwrite=False,
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
931
            revision=None, verbose=False,
4056.6.1 by Gary van der Merwe
Add --local option to pull.
932
            directory=None, local=False):
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
933
        # FIXME: too much stuff is in the command class
1551.14.11 by Aaron Bentley
rename rev_id and other_rev_id
934
        revision_id = None
1551.14.7 by Aaron Bentley
test suite fixes
935
        mergeable = None
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
936
        if directory is None:
937
            directory = u'.'
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
938
        try:
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
939
            tree_to = WorkingTree.open_containing(directory)[0]
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
940
            branch_to = tree_to.branch
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
941
            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
942
        except errors.NoWorkingTree:
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
943
            tree_to = None
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
944
            branch_to = Branch.open_containing(directory)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
945
            self.add_cleanup(branch_to.lock_write().unlock)
5147.1.1 by Andrew Bennetts
Avoid relocking in cmd_pull.
946
4056.6.4 by Gary van der Merwe
Implement pull --local.
947
        if local and not branch_to.get_bound_location():
948
            raise errors.LocalRequiresBoundBranch()
1711.3.3 by John Arbash Meinel
Allow pull to use a bundle as a target,
949
2817.4.3 by Vincent Ladeuil
Add tests for commit, reuse master branch transport.
950
        possible_transports = []
1711.3.3 by John Arbash Meinel
Allow pull to use a bundle as a target,
951
        if location is not None:
3251.4.10 by Aaron Bentley
Pull of launchpad locations works (abentley, #181945)
952
            try:
953
                mergeable = bundle.read_mergeable_from_url(location,
954
                    possible_transports=possible_transports)
955
            except errors.NotABundle:
956
                mergeable = None
1711.3.3 by John Arbash Meinel
Allow pull to use a bundle as a target,
957
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
958
        stored_loc = branch_to.get_parent()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
959
        if location is None:
960
            if stored_loc is None:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
961
                raise errors.BzrCommandError("No pull location known or"
962
                                             " specified.")
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
963
            else:
1685.1.58 by Martin Pool
urlutils.unescape_for_display should return Unicode
964
                display_url = urlutils.unescape_for_display(stored_loc,
965
                        self.outf.encoding)
3200.1.1 by James Westby
Make pull --quiet more quiet. Fixes #185907.
966
                if not is_quiet():
3596.3.1 by James Westby
Give the user a bit more information about which saved location is being used.
967
                    self.outf.write("Using saved parent location: %s\n" % display_url)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
968
                location = stored_loc
1185.56.1 by Michael Ellerman
Simplify handling of DivergedBranches in cmd_pull()
969
3993.1.1 by Ian Clatworthy
helper function when only one revision required (Daniel Watkins)
970
        revision = _get_one_revision('pull', revision)
1551.14.4 by Aaron Bentley
Change bundle reader and merge directive to both be 'mergeables'
971
        if mergeable is not None:
972
            if revision is not None:
973
                raise errors.BzrCommandError(
974
                    'Cannot use -r with merge directives or bundles')
2520.4.109 by Aaron Bentley
start work on directive cherry-picking
975
            mergeable.install_revisions(branch_to.repository)
976
            base_revision_id, revision_id, verified = \
977
                mergeable.get_merge_request(branch_to.repository)
1711.3.3 by John Arbash Meinel
Allow pull to use a bundle as a target,
978
            branch_from = branch_to
979
        else:
3251.4.10 by Aaron Bentley
Pull of launchpad locations works (abentley, #181945)
980
            branch_from = Branch.open(location,
981
                possible_transports=possible_transports)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
982
            self.add_cleanup(branch_from.lock_read().unlock)
1711.3.3 by John Arbash Meinel
Allow pull to use a bundle as a target,
983
984
            if branch_to.get_parent() is None or remember:
985
                branch_to.set_parent(branch_from.base)
986
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.
987
        if revision is not None:
988
            revision_id = revision.as_revision_id(branch_from)
989
990
        if tree_to is not None:
991
            view_info = _get_view_info_for_change_reporter(tree_to)
992
            change_reporter = delta._ChangeReporter(
993
                unversioned_filter=tree_to.is_ignored,
994
                view_info=view_info)
995
            result = tree_to.pull(
996
                branch_from, overwrite, revision_id, change_reporter,
997
                possible_transports=possible_transports, local=local)
998
        else:
999
            result = branch_to.pull(
1000
                branch_from, overwrite, revision_id, local=local)
1001
1002
        result.report(self.outf)
1003
        if verbose and result.old_revid != result.new_revid:
1004
            log.show_branch_change(
1005
                branch_to, self.outf, result.old_revno,
1006
                result.old_revid)
1185.31.5 by John Arbash Meinel
Merged pull --verbose changes
1007
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1008
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1009
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
1010
    __doc__ = """Update a mirror of this branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1011
1649.1.1 by Robert Collins
* 'pull' and 'push' now normalise the revision history, so that any two
1012
    The target branch will not have its working tree populated because this
1013
    is both expensive, and is not supported on remote file systems.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1014
1649.1.1 by Robert Collins
* 'pull' and 'push' now normalise the revision history, so that any two
1015
    Some smart servers or protocols *may* put the working tree in place in
1016
    the future.
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1017
1018
    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
1019
    considered diverged if the destination branch's most recent commit is one
1020
    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.
1021
1022
    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
1023
    the other branch completely, discarding its unmerged changes.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1024
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1025
    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
1026
    do a merge (see bzr help merge) from the other branch, and commit that.
1027
    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
1028
1029
    If there is no default push location set, the first push will set it.
1030
    After that, you can omit the location to use the default.  To change the
1785.1.4 by John Arbash Meinel
Update help for the new --remember semantics.
1031
    default, use --remember. The value will only be saved if the remote
1032
    location can be accessed.
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1033
    """
1685.1.80 by Wouter van Heyst
more code cleanup
1034
2485.1.2 by James Westby
Update with comments from review, thanks to John and Aaron.
1035
    _see_also = ['pull', 'update', 'working-trees']
3256.1.2 by Daniel Watkins
Added revision argument to push.
1036
    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)
1037
        Option('create-prefix',
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
1038
               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
1039
                    'if it does not already exist.'),
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
1040
        custom_help('directory',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
1041
            help='Branch to push from, '
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
1042
                 '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)
1043
        Option('use-existing-dir',
1044
               help='By default push will fail if the target'
1045
                    ' 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
1046
                    ' 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)
1047
                    ' allow push to proceed.'),
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
1048
        Option('stacked',
1049
            help='Create a stacked branch that references the public location '
1050
                'of the parent branch.'),
1051
        Option('stacked-on',
3221.19.4 by Ian Clatworthy
shallow -> stacked
1052
            help='Create a stacked branch that refers to another branch '
3221.19.2 by Ian Clatworthy
tweaks to ui during review by igc
1053
                'for the commit history. Only the work not present in the '
1054
                'referenced branch is included in the branch created.',
3221.11.12 by Robert Collins
Basic push --reference support, requires url, slow.
1055
            type=unicode),
4420.1.2 by Vincent Ladeuil
Fix bug #284038 by adding a --strict option to push.
1056
        Option('strict',
1057
               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.
1058
               ' the working tree, --no-strict disables the check.'),
2279.3.1 by mbp at sourcefrog
Add a -d option to push, pull, merge (ported from tags branch)
1059
        ]
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1060
    takes_args = ['location?']
1185.85.31 by John Arbash Meinel
Updated bzr push, including bringing in the unused --verbose flag.
1061
    encoding_type = 'replace'
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1062
1495 by Robert Collins
Add a --create-prefix to the new push command.
1063
    def run(self, location=None, remember=False, overwrite=False,
3221.14.3 by Ian Clatworthy
Merge bzr.dev r3466
1064
        create_prefix=False, verbose=False, revision=None,
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
1065
        use_existing_dir=False, directory=None, stacked_on=None,
4420.1.2 by Vincent Ladeuil
Fix bug #284038 by adding a --strict option to push.
1066
        stacked=False, strict=None):
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
1067
        from bzrlib.push import _show_push_branch
1068
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
1069
        if directory is None:
1070
            directory = '.'
4420.1.2 by Vincent Ladeuil
Fix bug #284038 by adding a --strict option to push.
1071
        # Get the source branch
4453.1.4 by Vincent Ladeuil
Cleanup.
1072
        (tree, br_from,
1073
         _unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
4420.1.2 by Vincent Ladeuil
Fix bug #284038 by adding a --strict option to push.
1074
        # Get the tip's revision_id
3984.3.9 by Daniel Watkins
Converted cmd_push.
1075
        revision = _get_one_revision('push', revision)
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
1076
        if revision is not None:
3984.3.9 by Daniel Watkins
Converted cmd_push.
1077
            revision_id = revision.in_history(br_from).rev_id
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
1078
        else:
4294.2.1 by Robert Collins
Move directory checking for bzr push options into Branch.create_clone_on_transport.
1079
            revision_id = None
5147.2.2 by Vincent Ladeuil
Fix bug #519319 by defaulting to a warning for dirty trees.
1080
        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
1081
            tree.check_changed_or_out_of_date(
1082
                strict, 'push_strict',
1083
                more_error='Use --no-strict to force the push.',
1084
                more_warning='Uncommitted changes will not be pushed.')
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
1085
        # Get the stacked_on branch, if any
1086
        if stacked_on is not None:
1087
            stacked_on = urlutils.normalize_url(stacked_on)
3221.19.4 by Ian Clatworthy
shallow -> stacked
1088
        elif stacked:
3221.11.15 by Robert Collins
no parent branch causes an error on push --shallow.
1089
            parent_url = br_from.get_parent()
1090
            if parent_url:
1091
                parent = Branch.open(parent_url)
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
1092
                stacked_on = parent.get_public_branch()
1093
                if not stacked_on:
3221.11.17 by Robert Collins
no public location causes the parent to be used directly with push --shallow.
1094
                    # I considered excluding non-http url's here, thus forcing
1095
                    # 'public' branches only, but that only works for some
3221.14.3 by Ian Clatworthy
Merge bzr.dev r3466
1096
                    # 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.
1097
                    # error by the feedback given to them. RBC 20080227.
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
1098
                    stacked_on = parent_url
1099
            if not stacked_on:
3221.11.15 by Robert Collins
no parent branch causes an error on push --shallow.
1100
                raise errors.BzrCommandError(
1101
                    "Could not determine branch to refer to.")
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
1102
1103
        # Get the destination location
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1104
        if location is None:
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
1105
            stored_loc = br_from.get_push_location()
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1106
            if stored_loc is None:
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
1107
                raise errors.BzrCommandError(
1108
                    "No push location known or specified.")
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1109
            else:
1685.1.59 by Martin Pool
[broken] Fix up & refactor display of remembered urls to unescape properly
1110
                display_url = urlutils.unescape_for_display(stored_loc,
1111
                        self.outf.encoding)
3596.3.1 by James Westby
Give the user a bit more information about which saved location is being used.
1112
                self.outf.write("Using saved push location: %s\n" % display_url)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1113
                location = stored_loc
1685.1.22 by John Arbash Meinel
cmd_push was passing the location directly to relpath, rather than a URL
1114
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
1115
        _show_push_branch(br_from, revision_id, location, self.outf,
1116
            verbose=verbose, overwrite=overwrite, remember=remember,
3549.1.1 by Martin Pool
rename push --reference to --stacked-on
1117
            stacked_on=stacked_on, create_prefix=create_prefix,
3221.19.1 by Ian Clatworthy
refactor cmd_push to use a helper function
1118
            use_existing_dir=use_existing_dir)
1490 by Robert Collins
Implement a 'bzr push' command, with saved locations; update diff to return 1.
1119
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1120
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1121
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
1122
    __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;
1123
1124
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
1125
    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
1126
    If the FROM_LOCATION has no / or path separator embedded, the TO_LOCATION
1127
    is derived from the FROM_LOCATION by stripping a leading scheme or drive
1128
    identifier, if any. For example, "branch lp:foo-bar" will attempt to
1129
    create ./foo-bar.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1130
1131
    To retrieve the branch as of a particular revision, supply the --revision
1132
    parameter, as in "branch foo/bar -r 5".
1133
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1134
1135
    _see_also = ['checkout']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1136
    takes_args = ['from_location', 'to_location?']
5353.2.1 by John Arbash Meinel
Add flags to enable accelerator trees, but default them to false.
1137
    takes_options = ['revision',
1138
        Option('hardlink', help='Hard-link working tree files where possible.'),
5353.2.2 by John Arbash Meinel
update the test suite.
1139
        Option('files-from', type=str,
1140
               help="Get file contents from this tree."),
3983.1.1 by Daniel Watkins
Merged John Klinger's original work.
1141
        Option('no-tree',
3983.1.2 by Daniel Watkins
Minor cleanup.
1142
            help="Create a branch without a working-tree."),
4596.2.1 by Lukáš Lalinský
Add support for `bzr branch --switch`
1143
        Option('switch',
1144
            help="Switch the checkout in the current directory "
1145
                 "to the new branch."),
3221.20.3 by Ian Clatworthy
shallow -> stacked
1146
        Option('stacked',
1147
            help='Create a stacked branch referring to the source branch. '
3221.11.20 by Robert Collins
Support --shallow on branch.
1148
                'The new branch will depend on the availability of the source '
1149
                'branch for all operations.'),
3696.2.3 by Daniel Watkins
Added --standalone option to branch.
1150
        Option('standalone',
1151
               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.
1152
        Option('use-existing-dir',
1153
               help='By default branch will fail if the target'
1154
                    ' directory exists, but does not already'
1155
                    ' have a control directory.  This flag will'
1156
                    ' allow branch to proceed.'),
4927.3.1 by Ian Clatworthy
branch --bind option
1157
        Option('bind',
1158
            help="Bind new branch to from location."),
3221.11.20 by Robert Collins
Support --shallow on branch.
1159
        ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1160
    aliases = ['get', 'clone']
1161
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1162
    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.
1163
            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.
1164
            use_existing_dir=False, switch=False, bind=False,
5353.2.2 by John Arbash Meinel
update the test suite.
1165
            files_from=None):
4596.2.1 by Lukáš Lalinský
Add support for `bzr branch --switch`
1166
        from bzrlib import switch as _mod_switch
2220.2.30 by Martin Pool
split out tag-merging code and add some tests
1167
        from bzrlib.tag import _merge_tags_if_possible
3123.5.11 by Aaron Bentley
Accelerate branching from a lightweight checkout
1168
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
1169
            from_location)
5353.2.2 by John Arbash Meinel
update the test suite.
1170
        if not (hardlink or files_from):
1171
            # accelerator_tree is usually slower because you have to read N
1172
            # files (no readahead, lots of seeks, etc), but allow the user to
1173
            # explicitly request it
5353.2.1 by John Arbash Meinel
Add flags to enable accelerator trees, but default them to false.
1174
            accelerator_tree = None
5353.2.2 by John Arbash Meinel
update the test suite.
1175
        if files_from is not None and files_from != from_location:
1176
            accelerator_tree = WorkingTree.open(files_from)
3984.3.7 by Daniel Watkins
Fixed incorrect calls.
1177
        revision = _get_one_revision('branch', revision)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1178
        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.
1179
        if revision is not None:
1180
            revision_id = revision.as_revision_id(br_from)
1181
        else:
1182
            # FIXME - wt.last_revision, fallback to branch, fall back to
1183
            # None or perhaps NULL_REVISION to mean copy nothing
1184
            # RBC 20060209
1185
            revision_id = br_from.last_revision()
1186
        if to_location is None:
1187
            to_location = urlutils.derive_to_location(from_location)
1188
        to_transport = transport.get_transport(to_location)
1185.17.3 by Martin Pool
[pick] larger read lock scope for branch command
1189
        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.
1190
            to_transport.mkdir('.')
1191
        except errors.FileExists:
1192
            if not use_existing_dir:
1193
                raise errors.BzrCommandError('Target directory "%s" '
1194
                    'already exists.' % to_location)
1185.8.4 by Aaron Bentley
Fixed branch -r
1195
            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.
1196
                try:
1197
                    bzrdir.BzrDir.open_from_transport(to_transport)
1198
                except errors.NotBranchError:
1199
                    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.
1200
                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.
1201
                    raise errors.AlreadyBranchError(to_location)
1202
        except errors.NoSuchFile:
1203
            raise errors.BzrCommandError('Parent of "%s" does not exist.'
1204
                                         % to_location)
1205
        try:
1206
            # preserve whatever source format we have.
1207
            dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
1208
                                        possible_transports=[to_transport],
1209
                                        accelerator_tree=accelerator_tree,
1210
                                        hardlink=hardlink, stacked=stacked,
1211
                                        force_new_repo=standalone,
1212
                                        create_tree_if_local=not no_tree,
1213
                                        source_branch=br_from)
1214
            branch = dir.open_branch()
1215
        except errors.NoSuchRevision:
1216
            to_transport.delete_tree('.')
1217
            msg = "The branch %s has no revision %s." % (from_location,
1218
                revision)
1219
            raise errors.BzrCommandError(msg)
1220
        _merge_tags_if_possible(br_from, branch)
1221
        # If the source branch is stacked, the new branch may
1222
        # be stacked whether we asked for that explicitly or not.
1223
        # We therefore need a try/except here and not just 'if stacked:'
1224
        try:
1225
            note('Created new stacked branch referring to %s.' %
1226
                branch.get_stacked_on_url())
1227
        except (errors.NotStacked, errors.UnstackableBranchFormat,
1228
            errors.UnstackableRepositoryFormat), e:
1229
            note('Branched %d revision(s).' % branch.revno())
4948.3.1 by Ian Clatworthy
branch --bind option
1230
        if bind:
1231
            # Bind to the parent
1232
            parent_branch = Branch.open(from_location)
1233
            branch.bind(parent_branch)
1234
            note('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.
1235
        if switch:
1236
            # Switch to the new branch
1237
            wt, _ = WorkingTree.open_containing('.')
1238
            _mod_switch.switch(wt.bzrdir, branch)
1239
            note('Switched to branch: %s',
1240
                urlutils.unescape_for_display(branch.base, 'utf-8'))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1241
1242
1508.1.20 by Robert Collins
Create a checkout command.
1243
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
1244
    __doc__ = """Create a new checkout of an existing branch.
1508.1.20 by Robert Collins
Create a checkout command.
1245
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1246
    If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
1247
    the branch found in '.'. This is useful if you have removed the working tree
1248
    or if it was never created - i.e. if you pushed the branch to its current
1249
    location using SFTP.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1250
1508.1.20 by Robert Collins
Create a checkout command.
1251
    If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
1252
    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
1253
    If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
1254
    is derived from the BRANCH_LOCATION by stripping a leading scheme or drive
1255
    identifier, if any. For example, "checkout lp:foo-bar" will attempt to
1256
    create ./foo-bar.
1508.1.20 by Robert Collins
Create a checkout command.
1257
1258
    To retrieve the branch as of a particular revision, supply the --revision
1259
    parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
1260
    out of date [so you cannot commit] but it may be useful (i.e. to examine old
1261
    code.)
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1262
    """
1508.1.20 by Robert Collins
Create a checkout command.
1263
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1264
    _see_also = ['checkouts', 'branch']
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1265
    takes_args = ['branch_location?', 'to_location?']
3984.3.5 by Daniel Watkins
Changed from option type to helper function.
1266
    takes_options = ['revision',
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
1267
                     Option('lightweight',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
1268
                            help="Perform a lightweight checkout.  Lightweight "
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
1269
                                 "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
1270
                                 "every operation.  Normal checkouts can perform "
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
1271
                                 "common operations like diff and status without "
1272
                                 "such access, and also support local commits."
1273
                            ),
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1274
                     Option('files-from', type=str,
1275
                            help="Get file contents from this tree."),
1276
                     Option('hardlink',
1277
                            help='Hard-link working tree files where possible.'
1278
                            ),
1587.1.14 by Robert Collins
Make bound branch creation happen via 'checkout'
1279
                     ]
1733.2.8 by Michael Ellerman
Add CVS compatible aliases for checkout and annotate, from fullermd.
1280
    aliases = ['co']
1508.1.20 by Robert Collins
Create a checkout command.
1281
2387.1.1 by Robert Collins
Remove the --basis parameter to clone etc. (Robert Collins)
1282
    def run(self, branch_location=None, to_location=None, revision=None,
5353.2.2 by John Arbash Meinel
update the test suite.
1283
            lightweight=False, files_from=None, hardlink=False):
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1284
        if branch_location is None:
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1285
            branch_location = osutils.getcwd()
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1286
            to_location = branch_location
3123.5.20 by Aaron Bentley
Checkout uses branch tree as a fallback accelerator
1287
        accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
1288
            branch_location)
5353.2.2 by John Arbash Meinel
update the test suite.
1289
        if not (hardlink or files_from):
1290
            # accelerator_tree is usually slower because you have to read N
1291
            # files (no readahead, lots of seeks, etc), but allow the user to
1292
            # explicitly request it
1293
            accelerator_tree = None
3984.3.7 by Daniel Watkins
Fixed incorrect calls.
1294
        revision = _get_one_revision('checkout', revision)
5353.2.2 by John Arbash Meinel
update the test suite.
1295
        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
1296
            accelerator_tree = WorkingTree.open(files_from)
3984.3.4 by Daniel Watkins
Converted cmd_checkout to use 1revision.
1297
        if revision is not None:
1298
            revision_id = revision.as_revision_id(source)
1508.1.20 by Robert Collins
Create a checkout command.
1299
        else:
1300
            revision_id = None
1301
        if to_location is None:
2512.4.1 by Ian Clatworthy
Fixes #115491 - 'branch lp:projname' now creates ./projname as exected
1302
            to_location = urlutils.derive_to_location(branch_location)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1303
        # if the source and to_location are the same,
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1304
        # and there is no working tree,
1305
        # then reconstitute a branch
1997.1.4 by Robert Collins
``bzr checkout --lightweight`` now operates on readonly branches as well
1306
        if (osutils.abspath(to_location) ==
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1307
            osutils.abspath(branch_location)):
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1308
            try:
1309
                source.bzrdir.open_workingtree()
1310
            except errors.NoWorkingTree:
1551.15.60 by Aaron Bentley
bzr checkout -r always works, even with -r0 (#127708)
1311
                source.bzrdir.create_workingtree(revision_id)
1508.1.28 by Robert Collins
Test using bzr checkout to reconstitute working trees.
1312
                return
3123.5.2 by Aaron Bentley
Allow checkout --files_from
1313
        source.create_checkout(to_location, revision_id, lightweight,
3136.1.3 by Aaron Bentley
Implement hard-link support for branch and checkout
1314
                               accelerator_tree, hardlink)
1508.1.20 by Robert Collins
Create a checkout command.
1315
1316
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1317
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
1318
    __doc__ = """Show list of renamed files.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1319
    """
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
1320
    # TODO: Option to show renames between two historical versions.
1321
1322
    # 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)
1323
    _see_also = ['status']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1324
    takes_args = ['dir?']
1325
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1326
    @display_command
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1327
    def run(self, dir=u'.'):
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1328
        tree = WorkingTree.open_containing(dir)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1329
        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.
1330
        new_inv = tree.inventory
1331
        old_tree = tree.basis_tree()
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1332
        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.
1333
        old_inv = old_tree.inventory
1334
        renames = []
1335
        iterator = tree.iter_changes(old_tree, include_unchanged=True)
1336
        for f, paths, c, v, p, n, k, e in iterator:
1337
            if paths[0] == paths[1]:
1338
                continue
1339
            if None in (paths):
1340
                continue
1341
            renames.append(paths)
1342
        renames.sort()
1343
        for old_name, new_name in renames:
1344
            self.outf.write("%s => %s\n" % (old_name, new_name))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1345
1346
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1347
class cmd_update(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
1348
    __doc__ = """Update a tree to have the latest code committed to its branch.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1349
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1350
    This will perform a merge into the working tree, and may generate
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1351
    conflicts. If you have any local changes, you will still
1587.1.10 by Robert Collins
update updates working tree and branch together.
1352
    need to commit them after the update for the update to be complete.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1353
1354
    If you want to discard your local changes, you can just do a
1587.1.10 by Robert Collins
update updates working tree and branch together.
1355
    'bzr revert' instead of 'bzr commit' after the update.
4916.1.11 by Martin Pool
Don't show extra message about updating from master; it's fairly redundant
1356
1357
    If the tree's branch is bound to a master branch, it will also update
1358
    the branch from the master.
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1359
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1360
2625.5.1 by Daniel Watkins
'bzr update's help now includes a see also reference to 'help status-flags'.
1361
    _see_also = ['pull', 'working-trees', 'status-flags']
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1362
    takes_args = ['dir?']
1907.5.1 by Matthieu Moy
update -r implemented
1363
    takes_options = ['revision']
1815.3.1 by Stefan (metze) Metzmacher
add 'up' as alias for 'update'
1364
    aliases = ['up']
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1365
1907.5.1 by Matthieu Moy
update -r implemented
1366
    def run(self, dir='.', revision=None):
1367
        if revision is not None and len(revision) != 1:
2009.1.4 by Mark Hammond
First attempt to merge .dev and resolve the conflicts (but tests are
1368
            raise errors.BzrCommandError(
1369
                        "bzr update --revision takes exactly one revision")
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1370
        tree = WorkingTree.open_containing(dir)[0]
1907.5.7 by Matthieu Moy
Coding style fixes thanks to jam.
1371
        branch = tree.branch
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
1372
        possible_transports = []
2009.1.6 by Mark Hammond
more tweaks of the merge to get the tests passing.
1373
        master = branch.get_master_branch(
2806.2.2 by Vincent Ladeuil
Fix #128076 and #131396 by reusing bound branch transport.
1374
            possible_transports=possible_transports)
2084.2.1 by Aaron Bentley
Support updating lightweight checkouts of readonly branches
1375
        if master is not None:
4879.1.1 by Neil Martinsen-Burrell
update provides feedback on which branch it is up to date with.
1376
            branch_location = master.base
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1377
            tree.lock_write()
2084.2.1 by Aaron Bentley
Support updating lightweight checkouts of readonly branches
1378
        else:
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1379
            branch_location = tree.branch.base
2084.2.1 by Aaron Bentley
Support updating lightweight checkouts of readonly branches
1380
            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.
1381
        self.add_cleanup(tree.unlock)
4879.1.3 by Vincent Ladeuil
Cleanup tests and tweak the text displayed.
1382
        # 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
1383
        branch_location = urlutils.unescape_for_display(
1384
            branch_location.rstrip('/'),
1385
            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.
1386
        existing_pending_merges = tree.get_parent_ids()[1:]
4900.1.4 by Andrew Bennetts
Merge lp:bzr
1387
        if master is None:
1388
            old_tip = None
1389
        else:
1390
            # may need to fetch data into a heavyweight checkout
1391
            # XXX: this may take some time, maybe we should display a
1392
            # message
1393
            old_tip = branch.update(possible_transports)
1394
        if revision is not None:
1395
            revision_id = revision[0].as_revision_id(branch)
1396
        else:
1397
            revision_id = branch.last_revision()
1398
        if revision_id == _mod_revision.ensure_null(tree.last_revision()):
5126.1.1 by Parth Malwankar
update -r now supports dotted revision.
1399
            revno = branch.revision_id_to_dotted_revno(revision_id)
1400
            note("Tree is up to date at revision %s of branch %s" %
1401
                ('.'.join(map(str, revno)), branch_location))
4900.1.4 by Andrew Bennetts
Merge lp:bzr
1402
            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.
1403
        view_info = _get_view_info_for_change_reporter(tree)
4900.1.4 by Andrew Bennetts
Merge lp:bzr
1404
        change_reporter = delta._ChangeReporter(
1405
            unversioned_filter=tree.is_ignored,
1406
            view_info=view_info)
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1407
        try:
4900.1.4 by Andrew Bennetts
Merge lp:bzr
1408
            conflicts = tree.update(
1409
                change_reporter,
1410
                possible_transports=possible_transports,
1411
                revision=revision_id,
1412
                old_tip=old_tip)
1413
        except errors.NoSuchRevision, e:
1414
            raise errors.BzrCommandError(
1415
                                  "branch has no revision %s\n"
1416
                                  "bzr update --revision only works"
1417
                                  " for a revision in the branch history"
1418
                                  % (e.revision))
5126.1.1 by Parth Malwankar
update -r now supports dotted revision.
1419
        revno = tree.branch.revision_id_to_dotted_revno(
4985.3.5 by Gerard Krol
Reverting some unneeded changes.
1420
            _mod_revision.ensure_null(tree.last_revision()))
5126.1.1 by Parth Malwankar
update -r now supports dotted revision.
1421
        note('Updated to revision %s of branch %s' %
1422
             ('.'.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
1423
        parent_ids = tree.get_parent_ids()
1424
        if parent_ids[1:] and parent_ids[1:] != existing_pending_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.
1425
            note('Your local commits will now show as pending merges with '
1426
                 "'bzr status', and can be committed with 'bzr commit'.")
1427
        if conflicts != 0:
1428
            return 1
1429
        else:
1430
            return 0
1508.1.24 by Robert Collins
Add update command for use with checkouts.
1431
1432
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1433
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
1434
    __doc__ = """Show information about a working tree, branch or repository.
1694.2.6 by Martin Pool
[merge] bzr.dev
1435
1436
    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)
1437
    tree, branch or repository.
4035.1.2 by Ian Clatworthy
clean-up trailing whitespace
1438
4032.2.1 by Ian Clatworthy
omit branch committers from info -v (now requires -vv)
1439
    In verbose mode, statistical information is included with each report.
1440
    To see extended statistic information, use a verbosity level of 2 or
1441
    higher by specifying the verbose option multiple times, e.g. -vv.
1694.2.6 by Martin Pool
[merge] bzr.dev
1442
1443
    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)
1444
1445
    :Examples:
1446
1447
      Display information on the format and related locations:
1448
1449
        bzr info
1450
1451
      Display the above together with extended format information and
1452
      basic statistics (like the number of files in the working tree and
1453
      number of revisions in the branch and repository):
1454
4217.3.1 by Ian Clatworthy
fix info help
1455
        bzr info -v
4032.2.1 by Ian Clatworthy
omit branch committers from info -v (now requires -vv)
1456
1457
      Display the above together with number of committers to the branch:
1458
4217.3.1 by Ian Clatworthy
fix info help
1459
        bzr info -vv
1694.2.6 by Martin Pool
[merge] bzr.dev
1460
    """
2485.1.2 by James Westby
Update with comments from review, thanks to John and Aaron.
1461
    _see_also = ['revno', 'working-trees', 'repositories']
1694.2.6 by Martin Pool
[merge] bzr.dev
1462
    takes_args = ['location?']
1624.3.21 by Olaf Conradi
Make bzr info command work on both local and remote locations. Support
1463
    takes_options = ['verbose']
2904.3.1 by Lukáš Lalinský
Unicode-safe output from ``bzr info``.
1464
    encoding_type = 'replace'
1694.2.6 by Martin Pool
[merge] bzr.dev
1465
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1466
    @display_command
2768.1.8 by Ian Clatworthy
Get test suite fully working again
1467
    def run(self, location=None, verbose=False):
1468
        if verbose:
4032.2.1 by Ian Clatworthy
omit branch committers from info -v (now requires -vv)
1469
            noise_level = get_verbosity_level()
2768.1.8 by Ian Clatworthy
Get test suite fully working again
1470
        else:
1471
            noise_level = 0
1694.2.6 by Martin Pool
[merge] bzr.dev
1472
        from bzrlib.info import show_bzrdir_info
1473
        show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
2904.3.1 by Lukáš Lalinský
Unicode-safe output from ``bzr info``.
1474
                         verbose=noise_level, outfile=self.outf)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1475
1476
2292.1.13 by Marius Kruger
* merge the unversion command back into the remove command,
1477
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
1478
    __doc__ = """Remove files or directories.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1479
3619.5.3 by Robert Collins
Review feedback.
1480
    This makes bzr stop tracking changes to the specified files. bzr will delete
1481
    them if they can easily be recovered using revert. If no options or
1482
    parameters are given bzr will scan for files that are being tracked by bzr
1483
    but missing in your tree and stop tracking them for you.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1484
    """
1551.6.26 by Aaron Bentley
Add support for remove --new
1485
    takes_args = ['file*']
2292.1.30 by Marius Kruger
* Minor text fixes.
1486
    takes_options = ['verbose',
3619.5.1 by Robert Collins
* ``bzr rm`` will now scan for files that are missing and remove just
1487
        Option('new', help='Only remove files that have never been committed.'),
2292.1.28 by Marius Kruger
* NEWS
1488
        RegistryOption.from_kwargs('file-deletion-strategy',
2681.1.7 by Aaron Bentley
Fix option grammar
1489
            'The file deletion mode to be used.',
2292.1.28 by Marius Kruger
* NEWS
1490
            title='Deletion Strategy', value_switches=True, enum_switch=False,
2292.1.30 by Marius Kruger
* Minor text fixes.
1491
            safe='Only delete files if they can be'
1492
                 ' safely recovered (default).',
4556.1.1 by Martin Pool
Make 'rm --keep' help more clear
1493
            keep='Delete from bzr but leave the working copy.',
2292.1.28 by Marius Kruger
* NEWS
1494
            force='Delete all the specified files, even if they can not be '
1495
                'recovered and even if they are non-empty directories.')]
3619.5.2 by Robert Collins
* ``bzr rm`` is now aliased to ``bzr del`` for the convenience of svn
1496
    aliases = ['rm', 'del']
1685.1.77 by Wouter van Heyst
WorkingTree.remove takes an optional output file
1497
    encoding_type = 'replace'
2292.1.1 by Marius Kruger
"bzr remove" and "bzr rm" will now remove the working file.
1498
2292.1.30 by Marius Kruger
* Minor text fixes.
1499
    def run(self, file_list, verbose=False, new=False,
2292.1.28 by Marius Kruger
* NEWS
1500
        file_deletion_strategy='safe'):
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
1501
        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.
1502
3794.5.38 by Mark Hammond
Restore missing (apparently pointless) block accidently removed.
1503
        if file_list is not None:
1504
            file_list = [f for f in file_list]
1505
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1506
        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.
1507
        # Heuristics should probably all move into tree.remove_smart or
1508
        # some such?
1509
        if new:
1510
            added = tree.changes_from(tree.basis_tree(),
1511
                specific_files=file_list).added
1512
            file_list = sorted([f[0] for f in added], reverse=True)
1513
            if len(file_list) == 0:
1514
                raise errors.BzrCommandError('No matching files.')
1515
        elif file_list is None:
1516
            # missing files show up in iter_changes(basis) as
1517
            # versioned-with-no-kind.
1518
            missing = []
1519
            for change in tree.iter_changes(tree.basis_tree()):
1520
                # Find paths in the working tree that have no kind:
1521
                if change[1][1] is not None and change[6][1] is None:
1522
                    missing.append(change[1][1])
1523
            file_list = sorted(missing, reverse=True)
1524
            file_deletion_strategy = 'keep'
1525
        tree.remove(file_list, verbose=verbose, to_file=self.outf,
1526
            keep_files=file_deletion_strategy=='keep',
1527
            force=file_deletion_strategy=='force')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1528
1529
1530
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
1531
    __doc__ = """Print file_id of a particular file or directory.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1532
1533
    The file_id is assigned when the file is first added and remains the
1534
    same through all revisions where the file exists, even when it is
1535
    moved or renamed.
1536
    """
1685.1.80 by Wouter van Heyst
more code cleanup
1537
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1538
    hidden = True
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1539
    _see_also = ['inventory', 'ls']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1540
    takes_args = ['filename']
1185.85.35 by John Arbash Meinel
Updated file-path
1541
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1542
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1543
    def run(self, filename):
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1544
        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.
1545
        i = tree.path2id(relpath)
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1546
        if i is None:
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
1547
            raise errors.NotVersionedError(filename)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1548
        else:
1685.1.80 by Wouter van Heyst
more code cleanup
1549
            self.outf.write(i + '\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1550
1551
1552
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
1553
    __doc__ = """Print path of file_ids to a file or directory.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1554
1555
    This prints one line for each directory down to the target,
1185.85.35 by John Arbash Meinel
Updated file-path
1556
    starting at the branch root.
1557
    """
1685.1.80 by Wouter van Heyst
more code cleanup
1558
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1559
    hidden = True
1560
    takes_args = ['filename']
1185.85.35 by John Arbash Meinel
Updated file-path
1561
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1562
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1563
    def run(self, filename):
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
1564
        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.
1565
        fid = tree.path2id(relpath)
1963.2.6 by Robey Pointer
pychecker is on crack; go back to using 'is None'.
1566
        if fid is None:
2067.3.1 by Martin Pool
Clean up BzrNewError, other exception classes and users.
1567
            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.
1568
        segments = osutils.splitpath(relpath)
1569
        for pos in range(1, len(segments) + 1):
1570
            path = osutils.joinpath(segments[:pos])
1571
            self.outf.write("%s\n" % tree.path2id(path))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1572
1573
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1574
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
1575
    __doc__ = """Reconcile bzr metadata in a branch.
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1576
1577
    This can correct data mismatches that may have been caused by
1578
    previous ghost operations or bzr upgrades. You should only
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1579
    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.'
1580
    advises you to run it.
1581
1582
    If a second branch is provided, cross-branch reconciliation is
1583
    also attempted, which will check that data like the tree root
1584
    id which was not present in very early bzr versions is represented
1585
    correctly in both branches.
1586
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1587
    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.'
1588
    a potential saving in disk space or performance gain.
1589
1590
    The branch *MUST* be on a listable system such as local disk or sftp.
1591
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1592
1593
    _see_also = ['check']
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1594
    takes_args = ['branch?']
1595
1596
    def run(self, branch="."):
1597
        from bzrlib.reconcile import reconcile
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
1598
        dir = bzrdir.BzrDir.open(branch)
1570.1.2 by Robert Collins
Import bzrtools' 'fix' command as 'bzr reconcile.'
1599
        reconcile(dir)
1600
1601
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1602
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
1603
    __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)
1604
1605
    _see_also = ['log']
1733.2.1 by Michael Ellerman
Add an optional location parameter to the 'revision-history' command.
1606
    takes_args = ['location?']
1607
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1608
    hidden = True
1185.85.36 by John Arbash Meinel
Working on tests for revision-history, ancestry, and diff
1609
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1610
    @display_command
1733.2.1 by Michael Ellerman
Add an optional location parameter to the 'revision-history' command.
1611
    def run(self, location="."):
1612
        branch = Branch.open_containing(location)[0]
1613
        for revid in branch.revision_history():
1733.2.4 by Michael Ellerman
Merge bzr.dev, fix minor conflict in cmd_revision_history().
1614
            self.outf.write(revid)
1185.85.36 by John Arbash Meinel
Working on tests for revision-history, ancestry, and diff
1615
            self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1616
1617
1225 by Martin Pool
- branch now tracks ancestry - all merged revisions
1618
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
1619
    __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)
1620
1621
    _see_also = ['log', 'revision-history']
1733.2.2 by Michael Ellerman
Add optional location to ancestry and fix behaviour for checkouts.
1622
    takes_args = ['location?']
1623
1225 by Martin Pool
- branch now tracks ancestry - all merged revisions
1624
    hidden = True
1185.85.36 by John Arbash Meinel
Working on tests for revision-history, ancestry, and diff
1625
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1626
    @display_command
1733.2.2 by Michael Ellerman
Add optional location to ancestry and fix behaviour for checkouts.
1627
    def run(self, location="."):
1628
        try:
1629
            wt = WorkingTree.open_containing(location)[0]
1630
        except errors.NoWorkingTree:
1631
            b = Branch.open(location)
1632
            last_revision = b.last_revision()
1633
        else:
1634
            b = wt.branch
1635
            last_revision = wt.last_revision()
1636
1637
        revision_ids = b.repository.get_ancestry(last_revision)
1668.1.14 by Martin Pool
merge olaf - InvalidRevisionId fixes
1638
        revision_ids.pop(0)
1639
        for revision_id in revision_ids:
1685.1.69 by Wouter van Heyst
merge bzr.dev 1740
1640
            self.outf.write(revision_id + '\n')
1225 by Martin Pool
- branch now tracks ancestry - all merged revisions
1641
1642
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1643
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
1644
    __doc__ = """Make a directory into a versioned branch.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1645
1646
    Use this to create an empty branch, or before importing an
1647
    existing project.
1648
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1649
    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
1650
    the history of the branch will be stored in the repository.  Otherwise
2374.1.2 by Ian Clatworthy
Improved after feedback from reviewers
1651
    init creates a standalone branch which carries its own history
1652
    in the .bzr directory.
1662.1.19 by Martin Pool
Better error message when initting existing tree
1653
1654
    If there is already a branch at the location but it has no working tree,
1655
    the tree can be populated with 'bzr checkout'.
1656
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
1657
    Recipe for importing a tree of files::
1658
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1659
        cd ~/project
1660
        bzr init
1185.12.93 by Aaron Bentley
Fixed obsolete help
1661
        bzr add .
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1662
        bzr status
3035.1.1 by John Arbash Meinel
Address bug #59302 and fix documentation that uses single quotes.
1663
        bzr commit -m "imported project"
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1664
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1665
2677.1.2 by Alexander Belchenko
bzr_man: see also topics as cross-reference links
1666
    _see_also = ['init-repository', 'branch', 'checkout']
1185.16.138 by Martin Pool
[patch] 'bzr init DIR' (John)
1667
    takes_args = ['location?']
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
1668
    takes_options = [
2524.1.1 by Aaron Bentley
Revert broken changes
1669
        Option('create-prefix',
1670
               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
1671
                    'if it does not already exist.'),
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1672
         RegistryOption('format',
1673
                help='Specify a format for this branch. '
1674
                'See "help formats".',
3224.5.2 by Andrew Bennetts
Avoid importing bzrlib.bzrdir unnecessarily.
1675
                lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1676
                converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
2241.1.19 by mbp at sourcefrog
(merge) trunk
1677
                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
1678
                title="Branch format",
2241.1.19 by mbp at sourcefrog
(merge) trunk
1679
                ),
2230.3.42 by Aaron Bentley
add --append-revisions-only option to init
1680
         Option('append-revisions-only',
1681
                help='Never change revnos or the existing log.'
1682
                '  Append revisions to it only.')
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1683
         ]
2524.1.1 by Aaron Bentley
Revert broken changes
1684
    def run(self, location=None, format=None, append_revisions_only=False,
1685
            create_prefix=False):
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
1686
        if format is None:
2204.5.5 by Aaron Bentley
Remove RepositoryFormat.set_default_format, deprecate get_format_type
1687
            format = bzrdir.format_registry.make_bzrdir('default')
1185.16.138 by Martin Pool
[patch] 'bzr init DIR' (John)
1688
        if location is None:
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
1689
            location = u'.'
1830.4.5 by Wouter van Heyst
cleanup
1690
1830.4.7 by Wouter van Heyst
review fixes, rename transport variable to to_transport
1691
        to_transport = transport.get_transport(location)
1830.4.5 by Wouter van Heyst
cleanup
1692
1693
        # The path has to exist to initialize a
1694
        # branch inside of it.
1695
        # Just using os.mkdir, since I don't
1696
        # believe that we want to create a bunch of
1697
        # locations if the user supplies an extended path
2524.1.1 by Aaron Bentley
Revert broken changes
1698
        try:
1699
            to_transport.ensure_base()
1700
        except errors.NoSuchFile:
1701
            if not create_prefix:
1702
                raise errors.BzrCommandError("Parent directory of %s"
1703
                    " does not exist."
1704
                    "\nYou may supply --create-prefix to create all"
1705
                    " leading parent directories."
1706
                    % location)
4294.2.1 by Robert Collins
Move directory checking for bzr push options into Branch.create_clone_on_transport.
1707
            to_transport.create_prefix()
2504.1.3 by Daniel Watkins
Implemented --create-prefix for 'init'.
1708
1654.1.4 by Robert Collins
Teach `bzr init` how to init at the root of a repository.
1709
        try:
3697.5.4 by John Arbash Meinel
Merge vila's init[-repo] changes and add a NEWS entry.
1710
            a_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
1711
        except errors.NotBranchError:
1662.1.19 by Martin Pool
Better error message when initting existing tree
1712
            # really a NotBzrDir error...
2476.3.11 by Vincent Ladeuil
Cosmetic changes.
1713
            create_branch = bzrdir.BzrDir.create_branch_convenience
2476.3.6 by Vincent Ladeuil
Fix the 'init connects multiple times' in a different way.
1714
            branch = create_branch(to_transport.base, format=format,
2476.3.8 by Vincent Ladeuil
Mark transports that need to be instrumented or refactored to check
1715
                                   possible_transports=[to_transport])
3697.5.4 by John Arbash Meinel
Merge vila's init[-repo] changes and add a NEWS entry.
1716
            a_bzrdir = branch.bzrdir
1654.1.4 by Robert Collins
Teach `bzr init` how to init at the root of a repository.
1717
        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
1718
            from bzrlib.transport.local import LocalTransport
3697.5.4 by John Arbash Meinel
Merge vila's init[-repo] changes and add a NEWS entry.
1719
            if a_bzrdir.has_branch():
1830.4.8 by Wouter van Heyst
clean up imports (and get if collapsing right)
1720
                if (isinstance(to_transport, LocalTransport)
3697.5.4 by John Arbash Meinel
Merge vila's init[-repo] changes and add a NEWS entry.
1721
                    and not a_bzrdir.has_workingtree()):
1830.4.1 by Wouter van Heyst
Allow bzr init to create remote branches
1722
                        raise errors.BranchExistsWithoutWorkingTree(location)
1723
                raise errors.AlreadyBranchError(location)
3697.5.4 by John Arbash Meinel
Merge vila's init[-repo] changes and add a NEWS entry.
1724
            branch = a_bzrdir.create_branch()
1725
            a_bzrdir.create_workingtree()
2230.3.42 by Aaron Bentley
add --append-revisions-only option to init
1726
        if append_revisions_only:
1727
            try:
1728
                branch.set_append_revisions_only(True)
1729
            except errors.UpgradeRequired:
1730
                raise errors.BzrCommandError('This branch format cannot be set'
4301.3.1 by Andrew Bennetts
Implement RemoteBranch.set_append_revisions_only.
1731
                    ' to append-revisions-only.  Try --default.')
3535.9.1 by Marius Kruger
print info after init and init-repo
1732
        if not is_quiet():
3922.2.1 by Marius Kruger
make `bzr init` less verbose, and update tests
1733
            from bzrlib.info import describe_layout, describe_format
1734
            try:
1735
                tree = a_bzrdir.open_workingtree(recommend_upgrade=False)
1736
            except (errors.NoWorkingTree, errors.NotLocalUrl):
1737
                tree = None
1738
            repository = branch.repository
1739
            layout = describe_layout(repository, branch, tree).lower()
1740
            format = describe_format(a_bzrdir, repository, branch, tree)
1741
            self.outf.write("Created a %s (format: %s)\n" % (layout, format))
1742
            if repository.is_shared():
1743
                #XXX: maybe this can be refactored into transport.path_or_url()
1744
                url = repository.bzrdir.root_transport.external_url()
1745
                try:
1746
                    url = urlutils.local_path_from_url(url)
1747
                except errors.InvalidURL:
1748
                    pass
1749
                self.outf.write("Using shared repository: %s\n" % url)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1750
1751
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
1752
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
1753
    __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)
1754
2485.1.2 by James Westby
Update with comments from review, thanks to John and Aaron.
1755
    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
1756
    revisions in the repository, not in the branch directory.  For branches
1757
    with shared history, this reduces the amount of storage needed and 
1758
    speeds up the creation of new branches.
2485.1.2 by James Westby
Update with comments from review, thanks to John and Aaron.
1759
4849.3.1 by Neil Martinsen-Burrell
add more description about what shared repositories are good for
1760
    If the --no-trees option is given then the branches in the repository
1761
    will not have working trees by default.  They will still exist as 
1762
    directories on disk, but they will not have separate copies of the 
1763
    files at a certain revision.  This can be useful for repositories that
1764
    store branches which are interacted with through checkouts or remote
1765
    branches, such as on a server.
1658.1.6 by Martin Pool
init-repo shouldn't insist on creating a new directory (Malone #38331)
1766
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
1767
    :Examples:
4849.3.1 by Neil Martinsen-Burrell
add more description about what shared repositories are good for
1768
        Create a shared repository holding just branches::
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
1769
1770
            bzr init-repo --no-trees repo
1771
            bzr init repo/trunk
1772
1773
        Make a lightweight checkout elsewhere::
1774
1775
            bzr checkout --lightweight repo/trunk trunk-checkout
1776
            cd trunk-checkout
1777
            (add files here)
1658.1.6 by Martin Pool
init-repo shouldn't insist on creating a new directory (Malone #38331)
1778
    """
2353.2.1 by John Arbash Meinel
(Wouter van Heyst) switch 'bzr init-repo' to default to '--no-trees'
1779
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
1780
    _see_also = ['init', 'branch', 'checkout', 'repositories']
2241.1.4 by Martin Pool
Moved old weave-based repository formats into bzrlib.repofmt.weaverepo.
1781
    takes_args = ["location"]
2221.4.9 by Aaron Bentley
Zap trailing whitespace
1782
    takes_options = [RegistryOption('format',
2221.4.12 by Aaron Bentley
Add option grouping to RegistryOption and clean up format options
1783
                            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
1784
                                 ' "bzr help formats" for details.',
3224.5.2 by Andrew Bennetts
Avoid importing bzrlib.bzrdir unnecessarily.
1785
                            lazy_registry=('bzrlib.bzrdir', 'format_registry'),
1786
                            converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
2221.4.12 by Aaron Bentley
Add option grouping to RegistryOption and clean up format options
1787
                            value_switches=True, title='Repository format'),
2257.2.1 by Wouter van Heyst
Change the ui level default for init-repo to --trees.
1788
                     Option('no-trees',
2353.2.1 by John Arbash Meinel
(Wouter van Heyst) switch 'bzr init-repo' to default to '--no-trees'
1789
                             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
1790
                                  ' not having a working tree.'),
2353.2.1 by John Arbash Meinel
(Wouter van Heyst) switch 'bzr init-repo' to default to '--no-trees'
1791
                    ]
1558.5.6 by Aaron Bentley
Renamed make-repo init-repo
1792
    aliases = ["init-repo"]
2353.2.1 by John Arbash Meinel
(Wouter van Heyst) switch 'bzr init-repo' to default to '--no-trees'
1793
2257.2.2 by Wouter van Heyst
Actually test that `bzr init-repo --{no,}-trees` still works
1794
    def run(self, location, format=None, no_trees=False):
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
1795
        if format is None:
2204.5.5 by Aaron Bentley
Remove RepositoryFormat.set_default_format, deprecate get_format_type
1796
            format = bzrdir.format_registry.make_bzrdir('default')
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
1797
1798
        if location is None:
1799
            location = '.'
1800
1830.4.7 by Wouter van Heyst
review fixes, rename transport variable to to_transport
1801
        to_transport = transport.get_transport(location)
2475.3.3 by John Arbash Meinel
Change calls to try/mkdir('.')/except FileExists to ensure_base()
1802
        to_transport.ensure_base()
1830.4.5 by Wouter van Heyst
cleanup
1803
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
1804
        newdir = format.initialize_on_transport(to_transport)
1558.5.2 by Aaron Bentley
Created *shared* repositories...
1805
        repo = newdir.create_repository(shared=True)
2257.2.2 by Wouter van Heyst
Actually test that `bzr init-repo --{no,}-trees` still works
1806
        repo.set_make_working_trees(not no_trees)
3535.9.1 by Marius Kruger
print info after init and init-repo
1807
        if not is_quiet():
1808
            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.
1809
            show_bzrdir_info(repo.bzrdir, verbose=0, outfile=self.outf)
1558.5.1 by Aaron Bentley
Added make-repository command
1810
1811
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1812
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
1813
    __doc__ = """Show differences in the working tree, between revisions or branches.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1814
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
1815
    If no arguments are given, all changes for the current tree are listed.
1816
    If files are given, only the changes in those files are listed.
1817
    Remote and multiple branches can be compared by using the --old and
1818
    --new options. If not provided, the default for both is derived from
1819
    the first argument, if any, or the current tree if no arguments are
1820
    given.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1821
1694.2.3 by Martin Pool
Add -p0, -p1 options for diff.
1822
    "bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1823
    produces patches suitable for "patch -p1".
1824
2961.2.1 by Guillermo Gonzalez
* fix Bug #147938 (add exit values reference for cmd_diff help)
1825
    :Exit values:
1826
        1 - changed
1827
        2 - unrepresentable changes
1828
        3 - error
1829
        0 - no change
1830
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
1831
    :Examples:
1832
        Shows the difference in the working tree versus the last commit::
1833
1834
            bzr diff
1835
1836
        Difference between the working tree and revision 1::
1837
1838
            bzr diff -r1
1839
4816.2.1 by Ian Clatworthy
Better explanation of diff -c behaviour
1840
        Difference between revision 3 and revision 1::
1841
1842
            bzr diff -r1..3
1843
1844
        Difference between revision 3 and revision 1 for branch xxx::
1845
1846
            bzr diff -r1..3 xxx
1847
1848
        To see the changes introduced in revision X::
1849
        
1850
            bzr diff -cX
1851
1852
        Note that in the case of a merge, the -c option shows the changes
1853
        compared to the left hand parent. To see the changes against
1854
        another parent, use::
1855
1856
            bzr diff -r<chosen_parent>..X
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
1857
4798.2.1 by Neil Martinsen-Burrell
add example of -c usage to diff help
1858
        The changes introduced by revision 2 (equivalent to -r1..2)::
1859
1860
            bzr diff -c2
1861
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
1862
        Show just the differences for file NEWS::
1863
1864
            bzr diff NEWS
1865
1866
        Show the differences in working tree xxx for file NEWS::
1867
1868
            bzr diff xxx/NEWS
1869
1870
        Show the differences from branch xxx to this working tree:
1871
1872
            bzr diff --old xxx
1873
1874
        Show the differences between two branches for file NEWS::
1875
3072.1.4 by Ian Clatworthy
Tweak help
1876
            bzr diff --old xxx --new yyy NEWS
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
1877
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
1878
        Same as 'bzr diff' but prefix paths with old/ and new/::
1879
1880
            bzr diff --prefix old/:new/
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1881
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1882
    _see_also = ['status']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1883
    takes_args = ['file*']
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
1884
    takes_options = [
2598.1.11 by Martin Pool
Insist that all options have a help string and fix those that don't.
1885
        Option('diff-options', type=str,
5349.1.1 by Matthäus G. Chajdas
Check if both --using and --diff-options are specified when calling diff and exit with error in this case. Change the documentation of --diff-options: Remove the 'external', so it is clear that these are the options passed to diff.
1886
               help='Pass these options to the diff program.'),
2193.3.1 by Martin Pool
Finish removal of global short-option table
1887
        Option('prefix', type=str,
1888
               short_name='p',
2852.1.1 by Vincent Ladeuil
Fix typo.
1889
               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
1890
                    'two values separated by a colon. (eg "old/:new/").'),
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
1891
        Option('old',
3118.1.2 by Ian Clatworthy
diff on branches without working trees (Ian Clatworthy, #6700)
1892
            help='Branch/tree to compare from.',
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
1893
            type=unicode,
1894
            ),
1895
        Option('new',
3118.1.2 by Ian Clatworthy
diff on branches without working trees (Ian Clatworthy, #6700)
1896
            help='Branch/tree to compare to.',
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
1897
            type=unicode,
1898
            ),
2598.1.11 by Martin Pool
Insist that all options have a help string and fix those that don't.
1899
        'revision',
2745.4.1 by Lukáš Lalinsky
New option -C/--change for diff and status to show changes in one revision. (#56299)
1900
        'change',
3123.6.2 by Aaron Bentley
Implement diff --using natively
1901
        Option('using',
1902
            help='Use this command to compare files.',
1903
            type=unicode,
1904
            ),
5131.1.1 by Jelmer Vernooij
Add --format option to 'bzr diff'.
1905
        RegistryOption('format',
1906
            help='Diff format to use.',
1907
            lazy_registry=('bzrlib.diff', 'format_registry'),
5131.1.3 by Jelmer Vernooij
Disable value switches for diff format.
1908
            value_switches=False, title='Diff format'),
2190.2.1 by Martin Pool
remove global registration of short options
1909
        ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1910
    aliases = ['di', 'dif']
1185.85.36 by John Arbash Meinel
Working on tests for revision-history, ancestry, and diff
1911
    encoding_type = 'exact'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1912
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1913
    @display_command
1684.1.6 by Martin Pool
(patch) --diff-prefix option (goffredo, alexander)
1914
    def run(self, revision=None, file_list=None, diff_options=None,
5131.1.1 by Jelmer Vernooij
Add --format option to 'bzr diff'.
1915
            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.
1916
        from bzrlib.diff import (get_trees_and_branches_to_diff_locked,
5131.1.1 by Jelmer Vernooij
Add --format option to 'bzr diff'.
1917
            show_diff_trees)
1684.1.6 by Martin Pool
(patch) --diff-prefix option (goffredo, alexander)
1918
1694.2.3 by Martin Pool
Add -p0, -p1 options for diff.
1919
        if (prefix is None) or (prefix == '0'):
1920
            # diff -p0 format
1694.2.1 by Martin Pool
Remove 'a/', 'b/' default prefixes on diff output.
1921
            old_label = ''
1922
            new_label = ''
1694.2.3 by Martin Pool
Add -p0, -p1 options for diff.
1923
        elif prefix == '1':
1924
            old_label = 'old/'
1925
            new_label = 'new/'
2197.2.1 by Martin Pool
Refactor cmd_diff
1926
        elif ':' in prefix:
1694.2.3 by Martin Pool
Add -p0, -p1 options for diff.
1927
            old_label, new_label = prefix.split(":")
2197.2.1 by Martin Pool
Refactor cmd_diff
1928
        else:
2324.1.1 by Dmitry Vasiliev
Small fixes for bzr diff
1929
            raise errors.BzrCommandError(
2325.1.2 by John Arbash Meinel
Add (eg "old/:new/") to errors to make it a little clearer.
1930
                '--prefix expects two values separated by a colon'
1931
                ' (eg "old/:new/")')
2197.2.1 by Martin Pool
Refactor cmd_diff
1932
5349.1.3 by Matthäus G. Chajdas
Fix issues raised by Parth Malwankar.
1933
        if using is not None and diff_options is not None:
1934
            raise errors.BzrCommandError(
1935
            '--diff-options and --using are mutually exclusive.')
5349.1.1 by Matthäus G. Chajdas
Check if both --using and --diff-options are specified when calling diff and exit with error in this case. Change the documentation of --diff-options: Remove the 'external', so it is clear that these are the options passed to diff.
1936
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.
1937
        if revision and len(revision) > 2:
1938
            raise errors.BzrCommandError('bzr diff --revision takes exactly'
1939
                                         ' one or two revision specifiers')
2325.1.2 by John Arbash Meinel
Add (eg "old/:new/") to errors to make it a little clearer.
1940
5131.1.2 by Jelmer Vernooij
Refuse both --using and --format to 'bzr diff'.
1941
        if using is not None and format is not None:
1942
            raise errors.BzrCommandError('--using and --format are mutually '
1943
                'exclusive.')
1944
4705.1.2 by Gary van der Merwe
Start on tests for get_trees_and_branches_to_diff.
1945
        (old_tree, new_tree,
1946
         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.
1947
         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.
1948
            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).
1949
        # GNU diff on Windows uses ANSI encoding for filenames
4797.57.10 by Alexander Belchenko
path_encoding selection logic extracted as helper function
1950
        path_encoding = osutils.get_diff_header_encoding()
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
1951
        return show_diff_trees(old_tree, new_tree, sys.stdout,
3072.1.1 by Ian Clatworthy
Improved diff based on feedback from abentley
1952
                               specific_files=specific_files,
1953
                               external_diff_options=diff_options,
1954
                               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).
1955
                               extra_trees=extra_trees,
5258.1.1 by Alexander Belchenko
merge diff header work from my 2.1 branch
1956
                               path_encoding=path_encoding,
1957
                               using=using,
5131.1.1 by Jelmer Vernooij
Add --format option to 'bzr diff'.
1958
                               format_cls=format)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1959
1960
1961
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
1962
    __doc__ = """List files deleted in the working tree.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1963
    """
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
1964
    # TODO: Show files deleted since a previous revision, or
1965
    # between two revisions.
1966
    # TODO: Much more efficient way to do this: read in new
1967
    # directories with readdir, rather than stating each one.  Same
1968
    # level of effort but possibly much less IO.  (Or possibly not,
1969
    # if the directories are very large...)
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1970
    _see_also = ['status', 'ls']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
1971
    takes_options = ['directory', 'show-ids']
1185.85.49 by John Arbash Meinel
Updated cmd_deleted, including adding --show-ids option.
1972
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1973
    @display_command
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
1974
    def run(self, show_ids=False, directory=u'.'):
1975
        tree = WorkingTree.open_containing(directory)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1976
        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.
1977
        old = tree.basis_tree()
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
1978
        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.
1979
        for path, ie in old.inventory.iter_entries():
1980
            if not tree.has_id(ie.file_id):
1981
                self.outf.write(path)
1982
                if show_ids:
1983
                    self.outf.write(' ')
1984
                    self.outf.write(ie.file_id)
1985
                self.outf.write('\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1986
1987
1988
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
1989
    __doc__ = """List files modified in working tree.
1551.10.13 by Aaron Bentley
Hide 'unknowns', document alterntatives to hidden commands
1990
    """
1551.10.14 by Aaron Bentley
Add some blank lines
1991
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
1992
    hidden = True
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
1993
    _see_also = ['status', 'ls']
5193.3.7 by Parth Malwankar
merged in changes from trunk and resolved conflict in builtins.py
1994
    takes_options = ['directory', 'null']
1551.10.14 by Aaron Bentley
Add some blank lines
1995
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
1996
    @display_command
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
1997
    def run(self, null=False, directory=u'.'):
1998
        tree = WorkingTree.open_containing(directory)[0]
1852.10.3 by Robert Collins
Remove all uses of compare_trees and replace with Tree.changes_from throughout bzrlib.
1999
        td = tree.changes_from(tree.basis_tree())
1398 by Robert Collins
integrate in Gustavos x-bit patch
2000
        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
2001
            if null:
2002
                self.outf.write(path + '\0')
2003
            else:
2004
                self.outf.write(osutils.quotefn(path) + '\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2005
2006
2007
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
2008
    __doc__ = """List files added in working tree.
1551.10.13 by Aaron Bentley
Hide 'unknowns', document alterntatives to hidden commands
2009
    """
1551.10.14 by Aaron Bentley
Add some blank lines
2010
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2011
    hidden = True
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2012
    _see_also = ['status', 'ls']
5193.3.7 by Parth Malwankar
merged in changes from trunk and resolved conflict in builtins.py
2013
    takes_options = ['directory', 'null']
1551.10.14 by Aaron Bentley
Add some blank lines
2014
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2015
    @display_command
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2016
    def run(self, null=False, directory=u'.'):
2017
        wt = WorkingTree.open_containing(directory)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2018
        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.
2019
        basis = wt.basis_tree()
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2020
        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.
2021
        basis_inv = basis.inventory
2022
        inv = wt.inventory
2023
        for file_id in inv:
2024
            if file_id in basis_inv:
2025
                continue
2026
            if inv.is_root(file_id) and len(basis_inv) == 0:
2027
                continue
2028
            path = inv.id2path(file_id)
5171.3.8 by Martin von Gagern
Fix error in bzr added --directory.
2029
            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.
2030
                continue
2031
            if null:
2032
                self.outf.write(path + '\0')
2033
            else:
2034
                self.outf.write(osutils.quotefn(path) + '\n')
1185.85.53 by John Arbash Meinel
Updated cmd_root
2035
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2036
2037
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
2038
    __doc__ = """Show the tree root directory.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2039
2040
    The root is the nearest enclosing directory with a .bzr control
2041
    directory."""
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2042
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2043
    takes_args = ['filename?']
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2044
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2045
    def run(self, filename=None):
2046
        """Print the branch root."""
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
2047
        tree = WorkingTree.open_containing(filename)[0]
1685.1.80 by Wouter van Heyst
more code cleanup
2048
        self.outf.write(tree.basedir + '\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2049
2050
2466.9.1 by Kent Gibson
add bzr log --limit
2051
def _parse_limit(limitstring):
2052
    try:
2053
        return int(limitstring)
2054
    except ValueError:
2055
        msg = "The limit argument must be an integer."
2056
        raise errors.BzrCommandError(msg)
2057
2058
3970.1.1 by Ian Clatworthy
log -n/--levels (Ian Clatworthy)
2059
def _parse_levels(s):
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
2060
    try:
2061
        return int(s)
2062
    except ValueError:
3970.1.1 by Ian Clatworthy
log -n/--levels (Ian Clatworthy)
2063
        msg = "The levels argument must be an integer."
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
2064
        raise errors.BzrCommandError(msg)
2065
2066
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2067
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
2068
    __doc__ = """Show historical log for a branch or subset of a branch.
3974.1.2 by Ian Clatworthy
enhanced log help
2069
2070
    log is bzr's default tool for exploring the history of a branch.
2071
    The branch to use is taken from the first parameter. If no parameters
2072
    are given, the branch containing the working directory is logged.
2073
    Here are some simple examples::
2074
2075
      bzr log                       log the current branch
2076
      bzr log foo.py                log a file in its branch
2077
      bzr log http://server/branch  log a branch on a server
2078
2079
    The filtering, ordering and information shown for each revision can
2080
    be controlled as explained below. By default, all revisions are
2081
    shown sorted (topologically) so that newer revisions appear before
2082
    older ones and descendants always appear before ancestors. If displayed,
2083
    merged revisions are shown indented under the revision in which they
2084
    were merged.
2085
2086
    :Output control:
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2087
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2088
      The log format controls how information about each revision is
2089
      displayed. The standard log formats are called ``long``, ``short``
2090
      and ``line``. The default is long. See ``bzr help log-formats``
2091
      for more details on log formats.
3974.1.2 by Ian Clatworthy
enhanced log help
2092
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2093
      The following options can be used to control what information is
2094
      displayed::
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2095
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2096
        -l N        display a maximum of N revisions
2097
        -n N        display N levels of revisions (0 for all, 1 for collapsed)
2098
        -v          display a status summary (delta) for each revision
2099
        -p          display a diff (patch) for each revision
2100
        --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.
2101
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2102
      Note that the default number of levels to display is a function of the
4206.1.1 by Ian Clatworthy
log mainline by default
2103
      log format. If the -n option is not used, the standard log formats show
2104
      just the top level (mainline).
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2105
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2106
      Status summaries are shown using status flags like A, M, etc. To see
2107
      the changes explained using words like ``added`` and ``modified``
2108
      instead, use the -vv option.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2109
3974.1.2 by Ian Clatworthy
enhanced log help
2110
    :Ordering control:
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2111
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2112
      To display revisions from oldest to newest, use the --forward option.
2113
      In most cases, using this option will have little impact on the total
2114
      time taken to produce a log, though --forward does not incrementally
2115
      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.
2116
3974.1.2 by Ian Clatworthy
enhanced log help
2117
    :Revision filtering:
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2118
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2119
      The -r option can be used to specify what revision or range of revisions
2120
      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.
2121
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2122
        -rX      display revision X
2123
        -rX..    display revision X and later
2124
        -r..Y    display up to and including revision Y
2125
        -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.
2126
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2127
      See ``bzr help revisionspec`` for details on how to specify X and Y.
2128
      Some common examples are given below::
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2129
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2130
        -r-1                show just the tip
2131
        -r-10..             show the last 10 mainline revisions
2132
        -rsubmit:..         show what's new on this branch
2133
        -rancestor:path..   show changes since the common ancestor of this
2134
                            branch and the one at location path
2135
        -rdate:yesterday..  show changes since yesterday
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2136
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2137
      When logging a range of revisions using -rX..Y, log starts at
2138
      revision Y and searches back in history through the primary
2139
      ("left-hand") parents until it finds X. When logging just the
2140
      top level (using -n1), an error is reported if X is not found
2141
      along the way. If multi-level logging is used (-n0), X may be
2142
      a nested merge revision and the log will be truncated accordingly.
2143
3974.1.2 by Ian Clatworthy
enhanced log help
2144
    :Path filtering:
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2145
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
2146
      If parameters are given and the first one is not a branch, the log
2147
      will be filtered to show only those revisions that changed the
2148
      nominated files or directories.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2149
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2150
      Filenames are interpreted within their historical context. To log a
2151
      deleted file, specify a revision range so that the file existed at
2152
      the end or start of the range.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2153
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2154
      Historical context is also important when interpreting pathnames of
2155
      renamed files/directories. Consider the following example:
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2156
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2157
      * revision 1: add tutorial.txt
2158
      * revision 2: modify tutorial.txt
2159
      * 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.
2160
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2161
      In this case:
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2162
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2163
      * ``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.
2164
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2165
      * ``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.
2166
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2167
      * ``bzr log -r2 -p tutorial.txt`` will show the changes made to
2168
        the original file in revision 2.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2169
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2170
      * ``bzr log -r2 -p guide.txt`` will display an error message as there
2171
        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.
2172
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2173
      Renames are always followed by log. By design, there is no need to
2174
      explicitly ask for this (and no way to stop logging a file back
2175
      until it was last renamed).
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2176
3974.1.2 by Ian Clatworthy
enhanced log help
2177
    :Other filtering:
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2178
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2179
      The --message option can be used for finding revisions that match a
2180
      regular expression in a commit message.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2181
3974.1.2 by Ian Clatworthy
enhanced log help
2182
    :Tips & tricks:
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2183
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2184
      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
2185
      line tools: you may prefer qlog or viz from qbzr or bzr-gtk, the
2186
      bzr-explorer shell, or the Loggerhead web interface.  See the Plugin
2187
      Guide <http://doc.bazaar.canonical.com/plugins/en/> and
2188
      <http://wiki.bazaar.canonical.com/IDEIntegration>.  
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2189
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2190
      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.
2191
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2192
        [ALIASES]
4206.1.1 by Ian Clatworthy
log mainline by default
2193
        tip = log -r-1
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
2194
        top = log -l10 --line
4206.1.1 by Ian Clatworthy
log mainline by default
2195
        show = log -v -p
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2196
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2197
      ``bzr tip`` will then show the latest revision while ``bzr top``
2198
      will show the last 10 mainline revisions. To see the details of a
2199
      particular revision X,  ``bzr show -rX``.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2200
4206.1.1 by Ian Clatworthy
log mainline by default
2201
      If you are interested in looking deeper into a particular merge X,
2202
      use ``bzr log -n0 -rX``.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2203
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2204
      ``bzr log -v`` on a branch with lots of history is currently
2205
      very slow. A fix for this issue is currently under development.
2206
      With or without that fix, it is recommended that a revision range
2207
      be given when using the -v option.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2208
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2209
      bzr has a generic full-text matching plugin, bzr-search, that can be
2210
      used to find revisions matching user names, commit messages, etc.
2211
      Among other features, this plugin can find all revisions containing
2212
      a list of words but not others.
4032.1.1 by John Arbash Meinel
Merge the removal of all trailing whitespace, and resolve conflicts.
2213
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2214
      When exploring non-mainline history on large projects with deep
2215
      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)
2216
      the historycache plugin. This plugin buffers historical information
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2217
      trading disk space for faster speed.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2218
    """
4202.2.1 by Ian Clatworthy
get directory logging working again
2219
    takes_args = ['file*']
3974.1.4 by Ian Clatworthy
log-formats topic and explained range searching
2220
    _see_also = ['log-formats', 'revisionspec']
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
2221
    takes_options = [
2222
            Option('forward',
2223
                   help='Show from oldest to newest.'),
3755.1.1 by Vincent Ladeuil
Fix --verbose leaking into blackbox tests.
2224
            'timezone',
2768.1.5 by Ian Clatworthy
Wrap new std verbose option with new help instead of declaring a new one
2225
            custom_help('verbose',
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
2226
                   help='Show files changed in each revision.'),
2227
            'show-ids',
2228
            'revision',
3734.1.1 by Vincent Ladeuil
Fix bug #248427 by adding a --change option to log.
2229
            Option('change',
2230
                   type=bzrlib.option._parse_revision_str,
2231
                   short_name='c',
2232
                   help='Show just the specified revision.'
2233
                   ' See also "help revisionspec".'),
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
2234
            'log-format',
4081.3.9 by Martin von Gagern
Use proper registry for --authors option.
2235
            RegistryOption('authors',
4081.3.11 by Martin von Gagern
List alternatives for --authors option.
2236
                '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.
2237
                title='Authors',
4081.3.9 by Martin von Gagern
Use proper registry for --authors option.
2238
                lazy_registry=('bzrlib.log', 'author_list_registry'),
4081.3.8 by Martin von Gagern
Use convenience RegistryOption for --authors option to log command.
2239
            ),
3947.1.10 by Ian Clatworthy
review feedback from vila
2240
            Option('levels',
3947.1.5 by Ian Clatworthy
rename --merge-revisions to --include-merges
2241
                   short_name='n',
3947.1.6 by Ian Clatworthy
log -n/--level-count N option
2242
                   help='Number of levels to display - 0 for all, 1 for flat.',
2243
                   argname='N',
3970.1.1 by Ian Clatworthy
log -n/--levels (Ian Clatworthy)
2244
                   type=_parse_levels),
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
2245
            Option('message',
2246
                   short_name='m',
2247
                   help='Show revisions whose message matches this '
2248
                        'regular expression.',
2249
                   type=str),
2250
            Option('limit',
3108.1.1 by Matt Nordhoff
bzr log: Add -l short name for the --limit argument.
2251
                   short_name='l',
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
2252
                   help='Limit the output to the first N revisions.',
2253
                   argname='N',
2254
                   type=_parse_limit),
3943.5.1 by Ian Clatworthy
first cut at log --show-diff
2255
            Option('show-diff',
3943.5.5 by Ian Clatworthy
tweak option name as requested in bug report
2256
                   short_name='p',
2257
                   help='Show changes made in each revision as a patch.'),
4221.2.1 by Ian Clatworthy
--include-merges as an alias for --levels 0 in log
2258
            Option('include-merges',
2259
                   help='Show merged revisions like --levels 0 does.'),
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
2260
            Option('exclude-common-ancestry',
2261
                   help='Display only the revisions that are not part'
2262
                   ' of both ancestries (require -rX..Y)'
2263
                   )
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
2264
            ]
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()
2265
    encoding_type = 'replace'
2266
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2267
    @display_command
4202.2.1 by Ian Clatworthy
get directory logging working again
2268
    def run(self, file_list=None, timezone='original',
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2269
            verbose=False,
2270
            show_ids=False,
2271
            forward=False,
2272
            revision=None,
3734.1.1 by Vincent Ladeuil
Fix bug #248427 by adding a --change option to log.
2273
            change=None,
1553.2.1 by Erik Bågfors
Support for plugins to register log formatters and set default formatter
2274
            log_format=None,
3947.1.10 by Ian Clatworthy
review feedback from vila
2275
            levels=None,
2466.9.1 by Kent Gibson
add bzr log --limit
2276
            message=None,
3943.5.1 by Ian Clatworthy
first cut at log --show-diff
2277
            limit=None,
4221.2.1 by Ian Clatworthy
--include-merges as an alias for --levels 0 in log
2278
            show_diff=False,
4081.3.2 by Martin von Gagern
Provide --authors argument to log command.
2279
            include_merges=False,
4081.3.15 by Gary van der Merwe
Merge bzr.dev.
2280
            authors=None,
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
2281
            exclude_common_ancestry=False,
2282
            ):
4202.2.5 by Ian Clatworthy
apply review tweaks & update help
2283
        from bzrlib.log import (
2284
            Logger,
2285
            make_log_request_dict,
2286
            _get_info_for_log_files,
2287
            )
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2288
        direction = (forward and 'forward') or 'reverse'
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
2289
        if (exclude_common_ancestry
2290
            and (revision is None or len(revision) != 2)):
2291
            raise errors.BzrCommandError(
2292
                '--exclude-common-ancestry requires -r with two revisions')
4221.2.2 by Ian Clatworthy
jam feedback: make --levels and --include-merges mutually exclusive
2293
        if include_merges:
2294
            if levels is None:
2295
                levels = 0
2296
            else:
2297
                raise errors.BzrCommandError(
2298
                    '--levels and --include-merges are mutually exclusive')
3734.1.1 by Vincent Ladeuil
Fix bug #248427 by adding a --change option to log.
2299
2300
        if change is not None:
2301
            if len(change) > 1:
2302
                raise errors.RangeInChangeOption()
2303
            if revision is not None:
2304
                raise errors.BzrCommandError(
2305
                    '--revision and --change are mutually exclusive')
2306
            else:
2307
                revision = change
2308
4202.2.1 by Ian Clatworthy
get directory logging working again
2309
        file_ids = []
2310
        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.
2311
        if file_list:
2312
            # find the file ids to log and check for directory filtering
2313
            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
2314
                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.
2315
            for relpath, file_id, kind in file_info_list:
2316
                if file_id is None:
2317
                    raise errors.BzrCommandError(
2318
                        "Path unknown at end or start of revision range: %s" %
2319
                        relpath)
2320
                # If the relpath is the top of the tree, we log everything
2321
                if relpath == '':
2322
                    file_ids = []
2323
                    break
4202.2.1 by Ian Clatworthy
get directory logging working again
2324
                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.
2325
                    file_ids.append(file_id)
2326
                filter_by_dir = filter_by_dir or (
2327
                    kind in ['directory', 'tree-reference'])
2328
        else:
2329
            # log everything
2330
            # FIXME ? log the current subdir only RBC 20060203
2331
            if revision is not None \
2332
                    and len(revision) > 0 and revision[0].get_branch():
2333
                location = revision[0].get_branch()
2334
            else:
2335
                location = '.'
2336
            dir, relpath = bzrdir.BzrDir.open_containing(location)
2337
            b = dir.open_branch()
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2338
            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.
2339
            rev1, rev2 = _get_revision_range(revision, b, self.name())
2340
2341
        # Decide on the type of delta & diff filtering to use
2342
        # TODO: add an --all-files option to make this configurable & consistent
2343
        if not verbose:
2344
            delta_type = None
2345
        else:
2346
            delta_type = 'full'
2347
        if not show_diff:
2348
            diff_type = None
2349
        elif file_ids:
2350
            diff_type = 'partial'
2351
        else:
2352
            diff_type = 'full'
2353
2354
        # Build the log formatter
2355
        if log_format is None:
2356
            log_format = log.log_formatter_registry.get_default(b)
2357
        # Make a non-encoding output to include the diffs - bug 328007
2358
        unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
2359
        lf = log_format(show_ids=show_ids, to_file=self.outf,
2360
                        to_exact_file=unencoded_output,
2361
                        show_timezone=timezone,
2362
                        delta_format=get_verbosity_level(),
2363
                        levels=levels,
4081.3.2 by Martin von Gagern
Provide --authors argument to log command.
2364
                        show_advice=levels is None,
4081.3.10 by Martin von Gagern
Renamed "authors" to "author_list_handler" in several places.
2365
                        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.
2366
2367
        # Choose the algorithm for doing the logging. It's annoying
2368
        # having multiple code paths like this but necessary until
2369
        # the underlying repository format is faster at generating
2370
        # deltas or can provide everything we need from the indices.
2371
        # The default algorithm - match-using-deltas - works for
2372
        # multiple files and directories and is faster for small
2373
        # amounts of history (200 revisions say). However, it's too
2374
        # slow for logging a single file in a repository with deep
2375
        # history, i.e. > 10K revisions. In the spirit of "do no
2376
        # evil when adding features", we continue to use the
2377
        # original algorithm - per-file-graph - for the "single
2378
        # file that isn't a directory without showing a delta" case.
2379
        partial_history = revision and b.repository._format.supports_chks
2380
        match_using_deltas = (len(file_ids) != 1 or filter_by_dir
2381
            or delta_type or partial_history)
2382
2383
        # Build the LogRequest and execute it
2384
        if len(file_ids) == 0:
2385
            file_ids = None
2386
        rqst = make_log_request_dict(
2387
            direction=direction, specific_fileids=file_ids,
2388
            start_revision=rev1, end_revision=rev2, limit=limit,
2389
            message_search=message, delta_type=delta_type,
5097.1.12 by Vincent Ladeuil
Implement the --exclude-common-ancestry log option.
2390
            diff_type=diff_type, _match_using_deltas=match_using_deltas,
2391
            exclude_common_ancestry=exclude_common_ancestry,
2392
            )
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.
2393
        Logger(b, rqst).show(lf)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2394
3943.6.3 by Ian Clatworthy
search the start tree if the end tree doesn't have a file
2395
3904.2.4 by Marius Kruger
* rename _get2Revisions to _get_revision_range
2396
def _get_revision_range(revisionspec_list, branch, command_name):
2397
    """Take the input of a revision option and turn it into a revision range.
2398
2399
    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
2400
    of the desired revisions. It does some user input validations.
3904.2.4 by Marius Kruger
* rename _get2Revisions to _get_revision_range
2401
    """
3904.2.1 by Marius Kruger
* factor out _get2Revisions from cmd_log to be able to reuse how revesions is determined by log.
2402
    if revisionspec_list is None:
2403
        rev1 = None
2404
        rev2 = None
2405
    elif len(revisionspec_list) == 1:
2406
        rev1 = rev2 = revisionspec_list[0].in_history(branch)
2407
    elif len(revisionspec_list) == 2:
3936.3.21 by Ian Clatworthy
make log -rX.. as fast as log -rX..-1
2408
        start_spec = revisionspec_list[0]
2409
        end_spec = revisionspec_list[1]
2410
        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.
2411
            # b is taken from revision[0].get_branch(), and
2412
            # show_log will use its revision_history. Having
2413
            # different branches will lead to weird behaviors.
2414
            raise errors.BzrCommandError(
3904.2.4 by Marius Kruger
* rename _get2Revisions to _get_revision_range
2415
                "bzr %s doesn't accept two revisions in different"
2416
                " branches." % command_name)
5092.1.2 by Vincent Ladeuil
Fix bug #519862.
2417
        if start_spec.spec is None:
2418
            # Avoid loading all the history.
5092.1.3 by Vincent Ladeuil
Tweak to fix failing test in the full test suite.
2419
            rev1 = RevisionInfo(branch, None, None)
5092.1.2 by Vincent Ladeuil
Fix bug #519862.
2420
        else:
2421
            rev1 = start_spec.in_history(branch)
3936.3.21 by Ian Clatworthy
make log -rX.. as fast as log -rX..-1
2422
        # Avoid loading all of history when we know a missing
2423
        # end of range means the last revision ...
3936.3.40 by Ian Clatworthy
review feedback from jam
2424
        if end_spec.spec is None:
3936.3.21 by Ian Clatworthy
make log -rX.. as fast as log -rX..-1
2425
            last_revno, last_revision_id = branch.last_revision_info()
2426
            rev2 = RevisionInfo(branch, last_revno, last_revision_id)
2427
        else:
2428
            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.
2429
    else:
2430
        raise errors.BzrCommandError(
2431
            'bzr %s --revision takes one or two values.' % command_name)
2432
    return rev1, rev2
1185.85.4 by John Arbash Meinel
currently broken, trying to fix things up.
2433
3921.3.4 by Marius Kruger
add support to filter on local and remote revisions
2434
2435
def _revision_range_to_revid_range(revision_range):
2436
    rev_id1 = None
2437
    rev_id2 = None
2438
    if revision_range[0] is not None:
2439
        rev_id1 = revision_range[0].rev_id
2440
    if revision_range[1] is not None:
2441
        rev_id2 = revision_range[1].rev_id
2442
    return rev_id1, rev_id2
2443
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
2444
def get_log_format(long=False, short=False, line=False, default='long'):
2445
    log_format = default
2446
    if long:
2447
        log_format = 'long'
2448
    if short:
2449
        log_format = 'short'
2450
    if line:
2451
        log_format = 'line'
2452
    return log_format
2453
2454
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2455
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
2456
    __doc__ = """Return revision-ids which affected a particular file.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2457
1685.1.80 by Wouter van Heyst
more code cleanup
2458
    A more user-friendly interface is "bzr log FILE".
2459
    """
2460
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2461
    hidden = True
2462
    takes_args = ["filename"]
1185.85.55 by John Arbash Meinel
Updated cmd_touching_revisions
2463
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2464
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2465
    def run(self, filename):
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
2466
        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.
2467
        file_id = tree.path2id(relpath)
1508.1.4 by Robert Collins
Convert most of the front ends commands to use WorkingTree.open_containing
2468
        b = tree.branch
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2469
        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.
2470
        touching_revs = log.find_touching_revisions(b, file_id)
2471
        for revno, revision_id, what in touching_revs:
2472
            self.outf.write("%6d %s\n" % (revno, what))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2473
2474
2475
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
2476
    __doc__ = """List files in a tree.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2477
    """
1551.9.24 by Aaron Bentley
Unhide ls, add kind flag
2478
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2479
    _see_also = ['status', 'cat']
2215.3.1 by Aaron Bentley
Allow ls to take a PATH
2480
    takes_args = ['path?']
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
2481
    takes_options = [
2482
            'verbose',
2483
            'revision',
4206.2.1 by Ian Clatworthy
ls should be non-recursive by default
2484
            Option('recursive', short_name='R',
2485
                   help='Recurse into subdirectories.'),
5193.3.3 by Parth Malwankar
removed -l for --from-root as that can be confusing as ls -l
2486
            Option('from-root',
2598.1.3 by Martin Pool
Option help improvements (thanks jamesw)
2487
                   help='Print paths relative to the root of the branch.'),
5193.3.1 by Parth Malwankar
added short options for ls.
2488
            Option('unknown', short_name='u',
2489
                help='Print unknown files.'),
3382.2.1 by Jerad Cramp
Fixed bug #165086. Command 'bzr ls' now accepts '-V' as an alias for '--versioned'.
2490
            Option('versioned', help='Print versioned files.',
2491
                   short_name='V'),
5193.3.1 by Parth Malwankar
added short options for ls.
2492
            Option('ignored', short_name='i',
2493
                help='Print ignored files.'),
2494
            Option('kind', short_name='k',
2598.1.12 by Martin Pool
Fix up --kind options
2495
                   help='List entries of a particular kind: file, directory, symlink.',
2496
                   type=unicode),
5193.3.4 by Parth Malwankar
--null is now a _standard_option
2497
            'null',
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
2498
            'show-ids',
5171.3.3 by Martin von Gagern
Add --directory option to ls, cat and annotate.
2499
            'directory',
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
2500
            ]
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2501
    @display_command
2598.1.12 by Martin Pool
Fix up --kind options
2502
    def run(self, revision=None, verbose=False,
4206.2.1 by Ian Clatworthy
ls should be non-recursive by default
2503
            recursive=False, from_root=False,
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
2504
            unknown=False, versioned=False, ignored=False,
5171.3.3 by Martin von Gagern
Add --directory option to ls, cat and annotate.
2505
            null=False, kind=None, show_ids=False, path=None, directory=None):
1551.9.24 by Aaron Bentley
Unhide ls, add kind flag
2506
2507
        if kind and kind not in ('file', 'directory', 'symlink'):
2508
            raise errors.BzrCommandError('invalid kind specified')
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
2509
2510
        if verbose and null:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
2511
            raise errors.BzrCommandError('Cannot set both --verbose and --null')
1551.6.36 by Aaron Bentley
Revert --debris/--detritus changes
2512
        all = not (unknown or versioned or ignored)
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
2513
1551.6.36 by Aaron Bentley
Revert --debris/--detritus changes
2514
        selection = {'I':ignored, '?':unknown, 'V':versioned}
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
2515
2215.3.1 by Aaron Bentley
Allow ls to take a PATH
2516
        if path is None:
2517
            fs_path = '.'
2518
        else:
2519
            if from_root:
2520
                raise errors.BzrCommandError('cannot specify both --from-root'
2521
                                             ' and PATH')
2522
            fs_path = path
5171.3.6 by Martin von Gagern
Fix --directory option to ls command.
2523
        tree, branch, relpath = \
5171.3.9 by Martin von Gagern
Rename function to _open_directory_or_containing_tree_or_branch.
2524
            _open_directory_or_containing_tree_or_branch(fs_path, directory)
4370.6.3 by Ian Clatworthy
minimise differences to trunk code
2525
2526
        # Calculate the prefix to use
2527
        prefix = None
1185.26.1 by John Arbash Meinel
Made ls work again, and take extra arguments.
2528
        if from_root:
4370.6.3 by Ian Clatworthy
minimise differences to trunk code
2529
            if relpath:
2530
                prefix = relpath + '/'
4832.1.1 by Benjamin Peterson
avoid getting extra slashes in the output when ls' argument ends with a slash
2531
        elif fs_path != '.' and not fs_path.endswith('/'):
4370.6.3 by Ian Clatworthy
minimise differences to trunk code
2532
            prefix = fs_path + '/'
4456.1.2 by Ian Clatworthy
fix tabs in builtins.py
2533
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
2534
        if revision is not None or tree is None:
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
2535
            tree = _get_one_revision_tree('ls', revision, branch=branch)
1551.6.36 by Aaron Bentley
Revert --debris/--detritus changes
2536
4032.4.5 by Eduardo Padoan
Check if the tree supports views only once when ls is called.
2537
        apply_view = False
4048.1.2 by Ian Clatworthy
fix broken test for ls -r
2538
        if isinstance(tree, WorkingTree) and tree.supports_views():
4032.4.2 by Eduardo Padoan
Make ls show only files on the current view.
2539
            view_files = tree.views.lookup_view()
2540
            if view_files:
4032.4.5 by Eduardo Padoan
Check if the tree supports views only once when ls is called.
2541
                apply_view = True
4032.4.2 by Eduardo Padoan
Make ls show only files on the current view.
2542
                view_str = views.view_display_str(view_files)
4210.1.1 by Ian Clatworthy
reword 'ignoring files outside view' message
2543
                note("Ignoring files outside view. View is %s" % view_str)
4032.4.2 by Eduardo Padoan
Make ls show only files on the current view.
2544
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2545
        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.
2546
        for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
2547
            from_dir=relpath, recursive=recursive):
2548
            # Apply additional masking
2549
            if not all and not selection[fc]:
2550
                continue
2551
            if kind is not None and fkind != kind:
2552
                continue
2553
            if apply_view:
2554
                try:
2555
                    if relpath:
2556
                        fullpath = osutils.pathjoin(relpath, fp)
2557
                    else:
2558
                        fullpath = fp
2559
                    views.check_path_in_view(tree, fullpath)
2560
                except errors.FileOutsideView:
2561
                    continue
4370.6.3 by Ian Clatworthy
minimise differences to trunk code
2562
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.
2563
            # Output the entry
2564
            if prefix:
2565
                fp = osutils.pathjoin(prefix, fp)
2566
            kindch = entry.kind_character()
2567
            outstring = fp + kindch
2568
            ui.ui_factory.clear_term()
2569
            if verbose:
2570
                outstring = '%-8s %s' % (fc, outstring)
2571
                if show_ids and fid is not None:
2572
                    outstring = "%-50s %s" % (outstring, fid)
2573
                self.outf.write(outstring + '\n')
2574
            elif null:
2575
                self.outf.write(fp + '\0')
2576
                if show_ids:
2577
                    if fid is not None:
2578
                        self.outf.write(fid)
2579
                    self.outf.write('\0')
2580
                self.outf.flush()
2581
            else:
2582
                if show_ids:
2583
                    if fid is not None:
2584
                        my_id = fid
2585
                    else:
2586
                        my_id = ''
2587
                    self.outf.write('%-50s %s\n' % (outstring, my_id))
2588
                else:
4456.1.1 by Ian Clatworthy
(igc) fix ls DIR --from-root and improve ls performance
2589
                    self.outf.write(outstring + '\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2590
4370.6.3 by Ian Clatworthy
minimise differences to trunk code
2591
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2592
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
2593
    __doc__ = """List unknown files.
1551.10.13 by Aaron Bentley
Hide 'unknowns', document alterntatives to hidden commands
2594
    """
1551.10.14 by Aaron Bentley
Add some blank lines
2595
1551.10.13 by Aaron Bentley
Hide 'unknowns', document alterntatives to hidden commands
2596
    hidden = True
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2597
    _see_also = ['ls']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2598
    takes_options = ['directory']
1551.10.14 by Aaron Bentley
Add some blank lines
2599
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2600
    @display_command
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2601
    def run(self, directory=u'.'):
2602
        for f in WorkingTree.open_containing(directory)[0].unknowns():
1773.4.2 by Martin Pool
Cleanup of imports; undeprecate all_revision_ids()
2603
            self.outf.write(osutils.quotefn(f) + '\n')
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2604
2605
2606
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
2607
    __doc__ = """Ignore specified files or patterns.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2608
3398.1.26 by Ian Clatworthy
jam feedback - make patterns a separate help topic
2609
    See ``bzr help patterns`` for details on the syntax of patterns.
2610
4800.2.2 by Patrick Regan
Reworded ignore to keep extra verbage down.
2611
    If a .bzrignore file does not exist, the ignore command
4800.2.1 by Patrick Regan
Added clarifying text about ignore command.
2612
    will create one and add the specified files or patterns to the newly
2613
    created file. The ignore command will also automatically add the 
4800.2.2 by Patrick Regan
Reworded ignore to keep extra verbage down.
2614
    .bzrignore file to be versioned. Creating a .bzrignore file without
4800.2.1 by Patrick Regan
Added clarifying text about ignore command.
2615
    the use of the ignore command will require an explicit add command.
2616
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2617
    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
2618
    After adding, editing or deleting that file either indirectly by
2619
    using this command or directly by using an editor, be sure to commit
2620
    it.
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
2621
    
5168.3.3 by Parth Malwankar
Removed --old-default-rules flag.
2622
    Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
2623
    the global ignore file can be found in the application data directory as
2624
    C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
5168.3.7 by Parth Malwankar
fixed doc.
2625
    Global ignores are not touched by this command. The global ignore file
5168.3.5 by Parth Malwankar
clarification on global ignores.
2626
    can be edited directly using an editor.
5168.3.3 by Parth Malwankar
Removed --old-default-rules flag.
2627
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
2628
    Patterns prefixed with '!' are exceptions to ignore patterns and take
2629
    precedence over regular ignores.  Such exceptions are used to specify
2630
    files that should be versioned which would otherwise be ignored.
2631
    
2632
    Patterns prefixed with '!!' act as regular ignore patterns, but have
2633
    precedence over the '!' exception patterns.
2135.2.2 by Kent Gibson
Ignore pattern matcher (glob.py) patches:
2634
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2635
    Note: ignore patterns containing shell wildcards must be quoted from
2135.2.2 by Kent Gibson
Ignore pattern matcher (glob.py) patches:
2636
    the shell on Unix.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2637
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2638
    :Examples:
2639
        Ignore the top level Makefile::
2640
2641
            bzr ignore ./Makefile
2642
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
2643
        Ignore .class files in all directories...::
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2644
3035.1.1 by John Arbash Meinel
Address bug #59302 and fix documentation that uses single quotes.
2645
            bzr ignore "*.class"
2646
4948.5.2 by John Whitley
NEWS and various documentation updates for ignore exclusions.
2647
        ...but do not ignore "special.class"::
2648
2649
            bzr ignore "!special.class"
2650
3035.1.1 by John Arbash Meinel
Address bug #59302 and fix documentation that uses single quotes.
2651
        Ignore .o files under the lib directory::
2652
2653
            bzr ignore "lib/**/*.o"
2654
2655
        Ignore .o files under the lib directory::
2656
2657
            bzr ignore "RE:lib/.*\.o"
3257.1.1 by Adeodato Simó
Add an example of some bzrignore cool stuff with Python regexes.
2658
2659
        Ignore everything but the "debian" toplevel directory::
2660
2661
            bzr ignore "RE:(?!debian/).*"
4948.5.7 by John Whitley
Terminology change: exclusion => exception.
2662
        
2663
        Ignore everything except the "local" toplevel directory,
2664
        but always ignore "*~" autosave files, even under local/::
2665
        
2666
            bzr ignore "*"
2667
            bzr ignore "!./local"
2668
            bzr ignore "!!*~"
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2669
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2670
3398.1.26 by Ian Clatworthy
jam feedback - make patterns a separate help topic
2671
    _see_also = ['status', 'ignored', 'patterns']
2063.5.1 by wang
"bzr ignore" takes multiple arguments. Fixes bug 29488.
2672
    takes_args = ['name_pattern*']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2673
    takes_options = ['directory',
5168.3.1 by Parth Malwankar
bzr ignore now support --default-rules option
2674
        Option('default-rules',
5168.3.3 by Parth Malwankar
Removed --old-default-rules flag.
2675
               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
2676
        ]
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2677
5171.3.11 by Martin von Gagern
merge from trunk.
2678
    def run(self, name_pattern_list=None, default_rules=None,
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2679
            directory=u'.'):
3528.2.1 by Jelmer Vernooij
Move functionality to add ignores to the ignore file into a separate function.
2680
        from bzrlib import ignores
5168.3.3 by Parth Malwankar
Removed --old-default-rules flag.
2681
        if default_rules is not None:
2682
            # dump the default rules and exit
2683
            for pattern in ignores.USER_DEFAULTS:
2684
                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.
2685
            return
2077.1.2 by Kent Gibson
Strip trailing slashes from ignore patterns (#4559).
2686
        if not name_pattern_list:
2063.5.5 by wang
resolve a conflict
2687
            raise errors.BzrCommandError("ignore requires at least one "
5168.3.3 by Parth Malwankar
Removed --old-default-rules flag.
2688
                "NAME_PATTERN or --default-rules.")
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2689
        name_pattern_list = [globbing.normalize_pattern(p)
2298.8.4 by Kent Gibson
Fix whitespace and alignment.
2690
                             for p in name_pattern_list]
5339.3.5 by Parth Malwankar
clean bad pattern handling code in cmd_ignore
2691
        bad_patterns = ''
5339.3.1 by Parth Malwankar
'bzr ignore' now fails on bad pattern.
2692
        for p in name_pattern_list:
2693
            if not globbing.Globster.is_pattern_valid(p):
5339.3.5 by Parth Malwankar
clean bad pattern handling code in cmd_ignore
2694
                bad_patterns += ('\n  %s' % p)
5339.3.1 by Parth Malwankar
'bzr ignore' now fails on bad pattern.
2695
        if bad_patterns:
5339.3.5 by Parth Malwankar
clean bad pattern handling code in cmd_ignore
2696
            msg = ('Invalid ignore pattern(s) found. %s' % bad_patterns)
2697
            ui.ui_factory.show_error(msg)
5339.3.1 by Parth Malwankar
'bzr ignore' now fails on bad pattern.
2698
            raise errors.InvalidPattern('')
2077.1.2 by Kent Gibson
Strip trailing slashes from ignore patterns (#4559).
2699
        for name_pattern in name_pattern_list:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2700
            if (name_pattern[0] == '/' or
2298.8.1 by Kent Gibson
Normalise ignore patterns to use '/' path separator.
2701
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
2077.1.2 by Kent Gibson
Strip trailing slashes from ignore patterns (#4559).
2702
                raise errors.BzrCommandError(
2703
                    "NAME_PATTERN should not be an absolute path")
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2704
        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.
2705
        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.
2706
        ignored = globbing.Globster(name_pattern_list)
2707
        matches = []
5326.1.1 by Parth Malwankar
locking for cmd_ignore is now in add_cleanup.
2708
        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.
2709
        for entry in tree.list_files():
2710
            id = entry[3]
2711
            if id is not None:
2712
                filename = entry[0]
2713
                if ignored.match(filename):
4988.8.3 by Ed Bayiates Home
More builtin command UIFactory updates
2714
                    matches.append(filename)
2747.5.1 by Daniel Watkins
'ignore' now outputs a list of versioned files that match the given pattern.
2715
        if len(matches) > 0:
4988.8.3 by Ed Bayiates Home
More builtin command UIFactory updates
2716
            self.outf.write("Warning: the following files are version controlled and"
2717
                  " match your ignore pattern:\n%s"
2718
                  "\nThese files will continue to be version controlled"
2719
                  " unless you 'bzr remove' them.\n" % ("\n".join(matches),))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2720
3603.3.1 by Robert Collins
* The help for ``bzr ignored`` now sugests ``bzr ls --ignored`` for
2721
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2722
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
2723
    __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
2724
2725
    List all the ignored files and the ignore pattern that caused the file to
2726
    be ignored.
2727
2728
    Alternatively, to list just the files::
2729
2730
        bzr ls --ignored
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2731
    """
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2732
3123.2.1 by Lukáš Lalinský
Use self.outf instead of sys.stdout in cmd_ignored.
2733
    encoding_type = 'replace'
3603.3.1 by Robert Collins
* The help for ``bzr ignored`` now sugests ``bzr ls --ignored`` for
2734
    _see_also = ['ignore', 'ls']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2735
    takes_options = ['directory']
3123.2.1 by Lukáš Lalinský
Use self.outf instead of sys.stdout in cmd_ignored.
2736
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2737
    @display_command
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2738
    def run(self, directory=u'.'):
2739
        tree = WorkingTree.open_containing(directory)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2740
        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.
2741
        for path, file_class, kind, file_id, entry in tree.list_files():
2742
            if file_class != 'I':
2743
                continue
2744
            ## XXX: Slightly inefficient since this was already calculated
2745
            pat = tree.is_ignored(path)
2746
            self.outf.write('%-50s %s\n' % (path, pat))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2747
2748
2749
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
2750
    __doc__ = """Lookup the revision-id from a revision-number
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2751
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2752
    :Examples:
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2753
        bzr lookup-revision 33
2754
    """
2755
    hidden = True
2756
    takes_args = ['revno']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2757
    takes_options = ['directory']
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2758
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2759
    @display_command
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2760
    def run(self, revno, directory=u'.'):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2761
        try:
2762
            revno = int(revno)
2763
        except ValueError:
4988.8.4 by Vincent Ladeuil
Fix lines too long, fix inverted assertions.
2764
            raise errors.BzrCommandError("not a valid revision-number: %r"
2765
                                         % revno)
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2766
        revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
4988.8.4 by Vincent Ladeuil
Fix lines too long, fix inverted assertions.
2767
        self.outf.write("%s\n" % revid)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2768
2769
2770
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
2771
    __doc__ = """Export current or past revision to a destination directory or archive.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2772
2773
    If no revision is specified this exports the last committed revision.
2774
2775
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
2776
    given, try to find the format with the extension. If no extension
2777
    is found exports to a directory (equivalent to --format=dir).
2778
2374.1.4 by Ian Clatworthy
Include feedback from mailing list.
2779
    If root is supplied, it will be used as the root directory inside
2780
    container formats (tar, zip, etc). If it is not supplied it will default
2781
    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
2782
2374.1.2 by Ian Clatworthy
Improved after feedback from reviewers
2783
    If branch is omitted then the branch containing the current working
2784
    directory will be used.
2099.1.1 by Daniel Silverstone
Add source branch support to export command
2785
2374.1.3 by Ian Clatworthy
Minor man page fixes for add, commit, export
2786
    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
2787
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2788
      =================       =========================
2789
      Supported formats       Autodetected by extension
2790
      =================       =========================
2666.1.5 by Ian Clatworthy
Incorporate feedback from Alex B. & James W.
2791
         dir                         (none)
1185.31.11 by John Arbash Meinel
Merging Alexander's zip export patch
2792
         tar                          .tar
2793
         tbz2                    .tar.bz2, .tbz2
2794
         tgz                      .tar.gz, .tgz
2795
         zip                          .zip
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
2796
      =================       =========================
1185.31.11 by John Arbash Meinel
Merging Alexander's zip export patch
2797
    """
3613.2.1 by Robert Collins
Teach export how to export a subdirectory. (Robert Collins)
2798
    takes_args = ['dest', 'branch_or_subdir?']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2799
    takes_options = ['directory',
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
2800
        Option('format',
2801
               help="Type of file to export to.",
2802
               type=unicode),
2803
        'revision',
3368.2.48 by Ian Clatworthy
apply first round of poolie's review feedback
2804
        Option('filters', help='Apply content filters to export the '
2805
                'convenient form.'),
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
2806
        Option('root',
2807
               type=str,
2808
               help="Name of the root directory inside the exported file."),
5076.2.3 by Jelmer Vernooij
Review comments from Rob.
2809
        Option('per-file-timestamps',
2810
               help='Set modification time of files to that of the last '
2811
                    'revision in which it was changed.'),
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
2812
        ]
3613.2.1 by Robert Collins
Teach export how to export a subdirectory. (Robert Collins)
2813
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2814
        root=None, filters=False, per_file_timestamps=False, directory=u'.'):
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
2815
        from bzrlib.export import export
2099.1.1 by Daniel Silverstone
Add source branch support to export command
2816
3613.2.1 by Robert Collins
Teach export how to export a subdirectory. (Robert Collins)
2817
        if branch_or_subdir is None:
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
2818
            tree = WorkingTree.open_containing(directory)[0]
2099.1.1 by Daniel Silverstone
Add source branch support to export command
2819
            b = tree.branch
3613.2.1 by Robert Collins
Teach export how to export a subdirectory. (Robert Collins)
2820
            subdir = None
2099.1.1 by Daniel Silverstone
Add source branch support to export command
2821
        else:
3613.2.1 by Robert Collins
Teach export how to export a subdirectory. (Robert Collins)
2822
            b, subdir = Branch.open_containing(branch_or_subdir)
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
2823
            tree = None
2824
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
2825
        rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
1185.31.12 by John Arbash Meinel
Refactored the export code to make it easier to add new export formats.
2826
        try:
5076.2.2 by Jelmer Vernooij
``bzr export`` now takes an optional argument ``--use-tree-timestamp``
2827
            export(rev_tree, dest, format, root, subdir, filtered=filters,
5076.2.3 by Jelmer Vernooij
Review comments from Rob.
2828
                   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.
2829
        except errors.NoSuchExportFormat, e:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
2830
            raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2831
2832
2833
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
2834
    __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
2835
2836
    If no revision is nominated, the last revision is used.
2837
2374.1.2 by Ian Clatworthy
Improved after feedback from reviewers
2838
    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
2839
    binary file.
2374.1.1 by Ian Clatworthy
Help and man page fixes
2840
    """
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2841
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
2842
    _see_also = ['ls']
5171.3.3 by Martin von Gagern
Add --directory option to ls, cat and annotate.
2843
    takes_options = ['directory',
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
2844
        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
2845
        Option('filters', help='Apply content filters to display the '
2846
                'convenience form.'),
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
2847
        'revision',
2848
        ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2849
    takes_args = ['filename']
2178.4.4 by Alexander Belchenko
encoding_type = 'exact' force sys.stdout to be binary stream on win32
2850
    encoding_type = 'exact'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2851
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2852
    @display_command
3368.2.31 by Ian Clatworthy
add --filters option to cat command
2853
    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.
2854
            filters=False, directory=None):
1185.50.9 by John Arbash Meinel
[bug 3632] Matthieu Moy- bzr cat should default to last revision
2855
        if revision is not None and len(revision) != 1:
2073.2.1 by wang
``bzr cat`` can look up contents of removed or renamed files. If the
2856
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
3063.4.1 by Lukáš Lalinský
Fix UnboundLocalError in cmd_cat.
2857
                                         " one revision specifier")
2858
        tree, branch, relpath = \
5171.3.9 by Martin von Gagern
Rename function to _open_directory_or_containing_tree_or_branch.
2859
            _open_directory_or_containing_tree_or_branch(filename, directory)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
2860
        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.
2861
        return self._run(tree, branch, relpath, filename, revision,
2862
                         name_from_revision, filters)
3010.1.17 by Robert Collins
Lock correctness and commit_group management for re-sign, in builtins.
2863
3368.2.31 by Ian Clatworthy
add --filters option to cat command
2864
    def _run(self, tree, b, relpath, filename, revision, name_from_revision,
2865
        filtered):
1907.4.5 by Matthieu Moy
Make bzr cat -r revno:N:foo consistant with bzr cat -r branch:foo.
2866
        if tree is None:
2158.1.1 by Wouter van Heyst
Fix #73500 mostly by catching a NotLocalUrl exception in cmd_cat.
2867
            tree = b.basis_tree()
3732.1.1 by Ian Clatworthy
fix bzr st -rbranch:path-to-branch (Lukas Lalinsky)
2868
        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
2869
        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
2870
2871
        old_file_id = rev_tree.path2id(relpath)
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
2872
2073.2.3 by wang
Change option name to --name-from-revision. Always make new tree the
2873
        if name_from_revision:
4112.1.1 by Vincent Ladeuil
Fallback to old revision id if the current one doesn't exist in
2874
            # Try in revision if requested
2073.2.1 by wang
``bzr cat`` can look up contents of removed or renamed files. If the
2875
            if old_file_id is None:
3655.3.1 by Lukáš Lalinský
Fix `bzr st -rbranch:PATH_TO_BRANCH`
2876
                raise errors.BzrCommandError(
2877
                    "%r is not present in revision %s" % (
2878
                        filename, rev_tree.get_revision_id()))
2073.2.1 by wang
``bzr cat`` can look up contents of removed or renamed files. If the
2879
            else:
3341.2.1 by Alexander Belchenko
`bzr cat` no more internally used Tree.print_file().
2880
                content = rev_tree.get_file_text(old_file_id)
2073.2.1 by wang
``bzr cat`` can look up contents of removed or renamed files. If the
2881
        else:
4112.1.1 by Vincent Ladeuil
Fallback to old revision id if the current one doesn't exist in
2882
            cur_file_id = tree.path2id(relpath)
2883
            found = False
2884
            if cur_file_id is not None:
2885
                # Then try with the actual file id
2886
                try:
2887
                    content = rev_tree.get_file_text(cur_file_id)
2888
                    found = True
2889
                except errors.NoSuchId:
2890
                    # The actual file id didn't exist at that time
2891
                    pass
2892
            if not found and old_file_id is not None:
2893
                # Finally try with the old file id
2894
                content = rev_tree.get_file_text(old_file_id)
2895
                found = True
2896
            if not found:
2897
                # Can't be found anywhere
2898
                raise errors.BzrCommandError(
2899
                    "%r is not present in revision %s" % (
2900
                        filename, rev_tree.get_revision_id()))
3368.2.31 by Ian Clatworthy
add --filters option to cat command
2901
        if filtered:
2902
            from bzrlib.filters import (
2903
                ContentFilterContext,
2904
                filtered_output_bytes,
2905
                )
3368.2.33 by Ian Clatworthy
expand filter context to support interesting stuff
2906
            filters = rev_tree._content_filter_stack(relpath)
3368.2.48 by Ian Clatworthy
apply first round of poolie's review feedback
2907
            chunks = content.splitlines(True)
2908
            content = filtered_output_bytes(chunks, filters,
3368.2.33 by Ian Clatworthy
expand filter context to support interesting stuff
2909
                ContentFilterContext(relpath, rev_tree))
4948.4.1 by Andrew Bennetts
Fix ObjectNotLocked error in cmd_cat (and also release locks slightly sooner).
2910
            self.cleanup_now()
3368.2.31 by Ian Clatworthy
add --filters option to cat command
2911
            self.outf.writelines(content)
2912
        else:
4948.4.1 by Andrew Bennetts
Fix ObjectNotLocked error in cmd_cat (and also release locks slightly sooner).
2913
            self.cleanup_now()
3368.2.31 by Ian Clatworthy
add --filters option to cat command
2914
            self.outf.write(content)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2915
2916
2917
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
2918
    __doc__ = """Show the offset in seconds from GMT to local time."""
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2919
    hidden = True
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
2920
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2921
    def run(self):
4988.8.3 by Ed Bayiates Home
More builtin command UIFactory updates
2922
        self.outf.write("%s\n" % osutils.local_time_offset())
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2923
2924
2925
2926
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
2927
    __doc__ = """Commit changes into a new revision.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
2928
4351.1.1 by Ian Clatworthy
improve commit help
2929
    An explanatory message needs to be given for each commit. This is
2930
    often done by using the --message option (getting the message from the
2931
    command line) or by using the --file option (getting the message from
2932
    a file). If neither of these options is given, an editor is opened for
2933
    the user to enter the message. To see the changed files in the
2934
    boilerplate text loaded into the editor, use the --show-diff option.
2935
2936
    By default, the entire tree is committed and the person doing the
2937
    commit is assumed to be the author. These defaults can be overridden
2938
    as explained below.
2939
2940
    :Selective commits:
2941
2942
      If selected files are specified, only changes to those files are
2943
      committed.  If a directory is specified then the directory and
2944
      everything within it is committed.
2945
  
2946
      When excludes are given, they take precedence over selected files.
2947
      For example, to commit only changes within foo, but not changes
2948
      within foo/bar::
2949
  
2950
        bzr commit foo -x foo/bar
2951
  
2952
      A selective commit after a merge is not yet supported.
2953
2954
    :Custom authors:
2955
2956
      If the author of the change is not the same person as the committer,
2957
      you can specify the author's name using the --author option. The
2958
      name should be in the same format as a committer-id, e.g.
2959
      "John Doe <jdoe@example.com>". If there is more than one author of
2960
      the change you can specify the option multiple times, once for each
2961
      author.
2962
  
2963
    :Checks:
2964
2965
      A common mistake is to forget to add a new file or directory before
2966
      running the commit command. The --strict option checks for unknown
2967
      files and aborts the commit if any are found. More advanced pre-commit
2968
      checks can be implemented by defining hooks. See ``bzr help hooks``
2969
      for details.
2970
2971
    :Things to note:
2972
2973
      If you accidentially commit the wrong changes or make a spelling
2974
      mistake in the commit message say, you can use the uncommit command
2975
      to undo it. See ``bzr help uncommit`` for details.
2976
2977
      Hooks can also be configured to run after a commit. This allows you
2978
      to trigger updates to external systems like bug trackers. The --fixes
2979
      option can be used to record the association between a revision and
2980
      one or more bugs. See ``bzr help bugs`` for details.
2981
2982
      A selective commit may fail in some cases where the committed
2983
      tree would be invalid. Consider::
2984
  
2985
        bzr init foo
2986
        mkdir foo/bar
2987
        bzr add foo/bar
2988
        bzr commit foo -m "committing foo"
2989
        bzr mv foo/bar foo/baz
2990
        mkdir foo/bar
2991
        bzr add foo/bar
2992
        bzr commit foo/bar -m "committing bar but not baz"
2993
  
2994
      In the example above, the last commit will fail by design. This gives
2995
      the user the opportunity to decide whether they want to commit the
2996
      rename at the same time, separately first, or not at all. (As a general
2997
      rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
2998
    """
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
2999
    # TODO: Run hooks on tree to-be-committed, and after commit.
3000
1185.16.65 by mbp at sourcefrog
- new commit --strict option
3001
    # TODO: Strict commit that fails if there are deleted files.
3002
    #       (what does "deleted files" mean ??)
3003
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
3004
    # TODO: Give better message for -s, --summary, used by tla people
3005
3006
    # XXX: verbose currently does nothing
3007
4351.1.1 by Ian Clatworthy
improve commit help
3008
    _see_also = ['add', 'bugs', 'hooks', 'uncommit']
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3009
    takes_args = ['selected*']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3010
    takes_options = [
3602.1.1 by Robert Collins
Add support for -x or --exclude to bzr commit, fixing bug 3117. (Robert Collins)
3011
            ListOption('exclude', type=str, short_name='x',
3012
                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.
3013
            Option('message', type=unicode,
3014
                   short_name='m',
3015
                   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
3016
            'verbose',
3017
             Option('unchanged',
3018
                    help='Commit even if nothing has changed.'),
3019
             Option('file', type=str,
3020
                    short_name='F',
3021
                    argname='msgfile',
3022
                    help='Take commit message from this file.'),
3023
             Option('strict',
3024
                    help="Refuse to commit if there are unknown "
3025
                    "files in the working tree."),
4766.2.1 by Alexander Sack
add --commit-time Option to built-in 'commit' command (LP: #459276)
3026
             Option('commit-time', type=str,
4766.2.2 by Andrew Bennetts
Add tests, and capture timezone offset as well as timestamp.
3027
                    help="Manually set a commit time using commit date "
3028
                    "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
3029
             ListOption('fixes', type=str,
3535.10.7 by James Westby
Make the --fixes option conform to the style guide check once more.
3030
                    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.
3031
                         "(see \"bzr help bugs\")."),
4056.2.1 by James Westby
Allow specifying multiple authors for a revision.
3032
             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.
3033
                    help="Set the author's name, if it's different "
3034
                         "from the committer."),
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3035
             Option('local',
3036
                    help="Perform a local commit in a bound "
3037
                         "branch.  Local commits are not pushed to "
3038
                         "the master branch until a normal commit "
3039
                         "is performed."
3040
                    ),
5193.1.1 by Parth Malwankar
added -p short option for 'commit --show-diff'
3041
             Option('show-diff', short_name='p',
4766.2.1 by Alexander Sack
add --commit-time Option to built-in 'commit' command (LP: #459276)
3042
                    help='When no message is supplied, show the diff along'
3043
                    ' with the status summary in the message editor.'),
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3044
             ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3045
    aliases = ['ci', 'checkin']
3046
4119.4.1 by Jonathan Lange
Extract bug fix encoding logic from commit.
3047
    def _iter_bug_fix_urls(self, fixes, branch):
2376.4.7 by jml at canonical
- Add docstrings to tests.
3048
        # Configure the properties for bug fixing attributes.
3049
        for fixed_bug in fixes:
3050
            tokens = fixed_bug.split(':')
3051
            if len(tokens) != 2:
3052
                raise errors.BzrCommandError(
3535.10.3 by James Westby
Talk about "trackers" rather than "tags" as it may be less confusing.
3053
                    "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.
3054
                    "See \"bzr help bugs\" for more information on this "
3055
                    "feature.\nCommit refused." % fixed_bug)
2376.4.7 by jml at canonical
- Add docstrings to tests.
3056
            tag, bug_id = tokens
3057
            try:
4119.4.1 by Jonathan Lange
Extract bug fix encoding logic from commit.
3058
                yield bugtracker.get_bug_url(tag, branch, bug_id)
2376.4.26 by Jonathan Lange
Tests for MalformedBugIdentifier and new error UnknownBugTrackerAbbreviation.
3059
            except errors.UnknownBugTrackerAbbreviation:
2376.4.7 by jml at canonical
- Add docstrings to tests.
3060
                raise errors.BzrCommandError(
3061
                    'Unrecognized bug %s. Commit refused.' % fixed_bug)
3535.10.9 by James Westby
Make the improved messages show up in the UI.
3062
            except errors.MalformedBugIdentifier, e:
2376.4.7 by jml at canonical
- Add docstrings to tests.
3063
                raise errors.BzrCommandError(
3535.10.9 by James Westby
Make the improved messages show up in the UI.
3064
                    "%s\nCommit refused." % (str(e),))
2376.4.7 by jml at canonical
- Add docstrings to tests.
3065
2768.1.5 by Ian Clatworthy
Wrap new std verbose option with new help instead of declaring a new one
3066
    def run(self, message=None, file=None, verbose=False, selected_list=None,
2817.4.4 by Vincent Ladeuil
Redo the lost modification.
3067
            unchanged=False, strict=False, local=False, fixes=None,
4766.2.1 by Alexander Sack
add --commit-time Option to built-in 'commit' command (LP: #459276)
3068
            author=None, show_diff=False, exclude=None, commit_time=None):
2598.6.30 by ghigo
- Updated the identation on the basis of Aaron suggestions
3069
        from bzrlib.errors import (
3070
            PointlessCommit,
3071
            ConflictsInTree,
3072
            StrictCommitFailed
3073
        )
3074
        from bzrlib.msgeditor import (
3075
            edit_commit_message_encoded,
3642.2.1 by Jelmer Vernooij
Add simple commit message template hook.
3076
            generate_commit_message_template,
2598.6.30 by ghigo
- Updated the identation on the basis of Aaron suggestions
3077
            make_commit_message_template_encoded
3078
        )
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3079
4766.2.2 by Andrew Bennetts
Add tests, and capture timezone offset as well as timestamp.
3080
        commit_stamp = offset = None
4766.2.1 by Alexander Sack
add --commit-time Option to built-in 'commit' command (LP: #459276)
3081
        if commit_time is not None:
4766.2.2 by Andrew Bennetts
Add tests, and capture timezone offset as well as timestamp.
3082
            try:
4766.2.1 by Alexander Sack
add --commit-time Option to built-in 'commit' command (LP: #459276)
3083
                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.
3084
            except ValueError, e:
3085
                raise errors.BzrCommandError(
3086
                    "Could not parse --commit-time: " + str(e))
4766.2.1 by Alexander Sack
add --commit-time Option to built-in 'commit' command (LP: #459276)
3087
1185.33.77 by Martin Pool
doc
3088
        # TODO: Need a blackbox test for invoking the external editor; may be
3089
        # slightly problematic to run this cross-platform.
3090
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3091
        # TODO: do more checks that the commit will succeed before
1185.33.72 by Martin Pool
Fix commit message template for non-ascii files, and add test for handling of
3092
        # spending the user's valuable time typing a commit message.
2376.4.2 by jml at canonical
More sophisticated error handling for --fixes option
3093
3094
        properties = {}
3095
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
3096
        tree, selected_list = WorkingTree.open_containing_paths(selected_list)
1704.2.11 by Martin Pool
Handle 'bzr commit DIR' when dir contains pending merges.
3097
        if selected_list == ['']:
3098
            # workaround - commit of root of tree should be exactly the same
3099
            # as just default commit in that tree, and succeed even though
3100
            # selected-file merge commit is not done yet
3101
            selected_list = []
3102
2817.4.4 by Vincent Ladeuil
Redo the lost modification.
3103
        if fixes is None:
3104
            fixes = []
4119.4.1 by Jonathan Lange
Extract bug fix encoding logic from commit.
3105
        bug_property = bugtracker.encode_fixes_bug_urls(
3106
            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
3107
        if bug_property:
3108
            properties['bugs'] = bug_property
2376.4.7 by jml at canonical
- Add docstrings to tests.
3109
1587.1.8 by Robert Collins
Local commits on unbound branches fail.
3110
        if local and not tree.branch.get_bound_location():
3111
            raise errors.LocalRequiresBoundBranch()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3112
4795.5.1 by Gioele Barabucci
Ask for confirmation if the commit message is a file name
3113
        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).
3114
            try:
4878.1.1 by Vincent Ladeuil
Fix babune failures when LC_ALL=C for bug #73073 fix using lexists not exists
3115
                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).
3116
            except UnicodeError:
3117
                # The commit message contains unicode characters that can't be
3118
                # represented in the filesystem encoding, so that can't be a
3119
                # file.
3120
                file_exists = False
3121
            if file_exists:
3122
                warning_msg = (
3123
                    'The commit message is a file name: "%(f)s".\n'
3124
                    '(use --file "%(f)s" to take commit message from that file)'
3125
                    % { 'f': message })
4795.5.13 by Gioele Barabucci
Do not check for interactivity
3126
                ui.ui_factory.show_warning(warning_msg)
5137.1.1 by Robert Collins
* ``bzr commit`` will prompt before using a commit message that was
3127
            if '\r' in message:
3128
                message = message.replace('\r\n', '\n')
3129
                message = message.replace('\r', '\n')
3130
            if file:
3131
                raise errors.BzrCommandError(
3132
                    "please specify either --message or --file")
4795.5.1 by Gioele Barabucci
Ask for confirmation if the commit message is a file name
3133
2149.1.4 by Aaron Bentley
Add additional test that callback is called with a Commit instance
3134
        def get_message(commit_obj):
2149.1.2 by Aaron Bentley
Defer getting the commit message until the revision is almost-committed
3135
            """Callback to get commit message"""
5137.1.1 by Robert Collins
* ``bzr commit`` will prompt before using a commit message that was
3136
            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
3137
                f = open(file)
4708.2.3 by Martin
Merge bzr.dev to unite with similar changes already made
3138
                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
3139
                    my_message = f.read().decode(osutils.get_user_encoding())
4708.2.3 by Martin
Merge bzr.dev to unite with similar changes already made
3140
                finally:
3141
                    f.close()
5137.1.1 by Robert Collins
* ``bzr commit`` will prompt before using a commit message that was
3142
            elif message is not None:
3143
                my_message = message
3144
            else:
3145
                # No message supplied: make one up.
3146
                # text is the status of the tree
3147
                text = make_commit_message_template_encoded(tree,
2598.6.30 by ghigo
- Updated the identation on the basis of Aaron suggestions
3148
                        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.
3149
                        output_encoding=osutils.get_user_encoding())
5086.6.1 by Robert Collins
Minor commit tidyup in preparation for hooking around revprops.
3150
                # 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
3151
                # XXX: Warning - looks like hooks return unicode,
3152
                # make_commit_message_template_encoded returns user encoding.
3153
                # We probably want to be using edit_commit_message instead to
3154
                # avoid this.
3642.2.1 by Jelmer Vernooij
Add simple commit message template hook.
3155
                start_message = generate_commit_message_template(commit_obj)
5137.1.1 by Robert Collins
* ``bzr commit`` will prompt before using a commit message that was
3156
                my_message = edit_commit_message_encoded(text,
3642.2.1 by Jelmer Vernooij
Add simple commit message template hook.
3157
                    start_message=start_message)
2149.1.2 by Aaron Bentley
Defer getting the commit message until the revision is almost-committed
3158
                if my_message is None:
3159
                    raise errors.BzrCommandError("please specify a commit"
3160
                        " message with either --message or --file")
3161
            if my_message == "":
3162
                raise errors.BzrCommandError("empty commit message specified")
3163
            return my_message
2376.4.2 by jml at canonical
More sophisticated error handling for --fixes option
3164
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.
3165
        # The API permits a commit with a filter of [] to mean 'select nothing'
3166
        # but the command line should not do that.
3167
        if not selected_list:
3168
            selected_list = None
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3169
        try:
2149.1.2 by Aaron Bentley
Defer getting the commit message until the revision is almost-committed
3170
            tree.commit(message_callback=get_message,
3171
                        specific_files=selected_list,
1607.1.5 by Robert Collins
Make commit verbose mode work!.
3172
                        allow_pointless=unchanged, strict=strict, local=local,
2789.2.1 by Ian Clatworthy
Make commit less verbose by default
3173
                        reporter=None, verbose=verbose, revprops=properties,
4766.2.1 by Alexander Sack
add --commit-time Option to built-in 'commit' command (LP: #459276)
3174
                        authors=author, timestamp=commit_stamp,
4766.2.2 by Andrew Bennetts
Add tests, and capture timezone offset as well as timestamp.
3175
                        timezone=offset,
5346.4.2 by Martin Pool
Move internal_tree_files and safe_relpath_files onto WorkingTree
3176
                        exclude=tree.safe_relpath_files(exclude))
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3177
        except PointlessCommit:
4351.1.2 by Ian Clatworthy
tweak grammar in error message
3178
            raise errors.BzrCommandError("No changes to commit."
3179
                              " Use --unchanged to commit anyhow.")
1185.14.10 by Aaron Bentley
Commit aborts with conflicts in the tree.
3180
        except ConflictsInTree:
1551.9.5 by Aaron Bentley
Revert broken save-commit-message code
3181
            raise errors.BzrCommandError('Conflicts detected in working '
3182
                'tree.  Use "bzr conflicts" to list, "bzr resolve FILE" to'
3183
                ' resolve.')
1185.16.65 by mbp at sourcefrog
- new commit --strict option
3184
        except StrictCommitFailed:
1551.9.5 by Aaron Bentley
Revert broken save-commit-message code
3185
            raise errors.BzrCommandError("Commit refused because there are"
3186
                              " 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
3187
        except errors.BoundBranchOutOfDate, e:
5066.1.1 by Gary van der Merwe
Make it possible to detect a BoundBranchOutOfDate from commit.
3188
            e.extra_help = ("\n"
3189
                'To commit to master branch, run update and then commit.\n'
3190
                'You can also pass --local to commit to continue working '
3191
                'disconnected.')
3192
            raise
2111.1.1 by Martin Pool
Fix #32054, save message if commit fails.
3193
3194
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3195
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
3196
    __doc__ = """Validate working tree structure, branch consistency and repository history.
3015.3.25 by Daniel Watkins
Updated help.
3197
3198
    This command checks various invariants about branch and repository storage
3199
    to detect data corruption or bzr bugs.
3200
3201
    The working tree and branch checks will only give output if a problem is
3202
    detected. The output fields of the repository check are:
2745.6.8 by Aaron Bentley
Clean up text
3203
4070.11.7 by Martin Pool
Correction to rest syntax for cmd_check
3204
    revisions
3205
        This is just the number of revisions checked.  It doesn't
3206
        indicate a problem.
3207
3208
    versionedfiles
3209
        This is just the number of versionedfiles checked.  It
3210
        doesn't indicate a problem.
3211
3212
    unreferenced ancestors
3213
        Texts that are ancestors of other texts, but
3214
        are not properly referenced by the revision ancestry.  This is a
3215
        subtle problem that Bazaar can work around.
3216
3217
    unique file texts
3218
        This is the total number of unique file contents
3219
        seen in the checked revisions.  It does not indicate a problem.
3220
3221
    repeated file texts
3222
        This is the total number of repeated texts seen
3223
        in the checked revisions.  Texts can be repeated when their file
3224
        entries are modified, but the file contents are not.  It does not
3225
        indicate a problem.
3015.4.14 by Daniel Watkins
Updated check help to explain what happens when no options are given.
3226
3015.4.19 by Daniel Watkins
Improved check docs.
3227
    If no restrictions are specified, all Bazaar data that is found at the given
3228
    location will be checked.
3229
3230
    :Examples:
3231
3232
        Check the tree and branch at 'foo'::
3233
3234
            bzr check --tree --branch foo
3235
3236
        Check only the repository at 'bar'::
3237
3238
            bzr check --repo bar
3239
3240
        Check everything at 'baz'::
3241
3242
            bzr check baz
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3243
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3244
3245
    _see_also = ['reconcile']
3015.3.2 by Daniel Watkins
Check.check now takes a path rather than a branch.
3246
    takes_args = ['path?']
3015.4.2 by Daniel Watkins
Made UI changes to include CLI options.
3247
    takes_options = ['verbose',
3248
                     Option('branch', help="Check the branch related to the"
3249
                                           " current directory."),
3250
                     Option('repo', help="Check the repository related to the"
3251
                                         " current directory."),
3252
                     Option('tree', help="Check the working tree related to"
3253
                                         " the current directory.")]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3254
3015.4.5 by Daniel Watkins
Each option selects only the specific thing to be checked.
3255
    def run(self, path=None, verbose=False, branch=False, repo=False,
3256
            tree=False):
3015.3.22 by Daniel Watkins
Changed 'check' to 'check_dwim'.
3257
        from bzrlib.check import check_dwim
3015.3.2 by Daniel Watkins
Check.check now takes a path rather than a branch.
3258
        if path is None:
3259
            path = '.'
3015.4.7 by Daniel Watkins
Vanilla 'bzr check' checks all items.
3260
        if not branch and not repo and not tree:
3261
            branch = repo = tree = True
3015.4.2 by Daniel Watkins
Made UI changes to include CLI options.
3262
        check_dwim(path, verbose, do_branch=branch, do_repo=repo, do_tree=tree)
1534.5.16 by Robert Collins
Review feedback.
3263
3264
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3265
class cmd_upgrade(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
3266
    __doc__ = """Upgrade branch storage to current format.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3267
3268
    The check command or bzr developers may sometimes advise you to run
1534.4.13 by Robert Collins
Give a reasonable warning on attempts to upgrade a readonly url.
3269
    this command. When the default format has changed you may also be warned
3270
    during other operations to upgrade.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3271
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3272
3273
    _see_also = ['check']
1534.4.13 by Robert Collins
Give a reasonable warning on attempts to upgrade a readonly url.
3274
    takes_args = ['url?']
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
3275
    takes_options = [
2221.4.9 by Aaron Bentley
Zap trailing whitespace
3276
                    RegistryOption('format',
2221.4.12 by Aaron Bentley
Add option grouping to RegistryOption and clean up format options
3277
                        help='Upgrade to a specific format.  See "bzr help'
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3278
                             ' formats" for details.',
3224.5.2 by Andrew Bennetts
Avoid importing bzrlib.bzrdir unnecessarily.
3279
                        lazy_registry=('bzrlib.bzrdir', 'format_registry'),
3280
                        converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
2221.4.12 by Aaron Bentley
Add option grouping to RegistryOption and clean up format options
3281
                        value_switches=True, title='Branch format'),
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
3282
                    ]
3283
3284
    def run(self, url='.', format=None):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3285
        from bzrlib.upgrade import upgrade
1857.1.20 by Aaron Bentley
Strip out all the EnumOption stuff
3286
        upgrade(url, format)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3287
3288
3289
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
3290
    __doc__ = """Show or set bzr user id.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3291
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
3292
    :Examples:
3293
        Show the email of the current user::
3294
3295
            bzr whoami --email
3296
3297
        Set the current user::
3298
3035.1.1 by John Arbash Meinel
Address bug #59302 and fix documentation that uses single quotes.
3299
            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
3300
    """
5171.3.15 by Martin von Gagern
Add --directory option to whoami.
3301
    takes_options = [ 'directory',
3302
                      Option('email',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3303
                             help='Display email address only.'),
1816.2.2 by Robey Pointer
fix 'whoami' to use encodings and allow setting the global or branch identity
3304
                      Option('branch',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3305
                             help='Set identity for the current branch instead of '
3306
                                  'globally.'),
1816.2.2 by Robey Pointer
fix 'whoami' to use encodings and allow setting the global or branch identity
3307
                    ]
3308
    takes_args = ['name?']
3309
    encoding_type = 'replace'
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3310
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
3311
    @display_command
5171.3.15 by Martin von Gagern
Add --directory option to whoami.
3312
    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
3313
        if name is None:
5171.3.15 by Martin von Gagern
Add --directory option to whoami.
3314
            if directory is None:
3315
                # use branch if we're inside one; otherwise global config
3316
                try:
3317
                    c = Branch.open_containing(u'.')[0].get_config()
3318
                except errors.NotBranchError:
3319
                    c = config.GlobalConfig()
3320
            else:
3321
                c = Branch.open(directory).get_config()
1816.2.4 by Robey Pointer
flesh out 'whoami' docs a little, and don't display the identity after setting it
3322
            if email:
1816.2.10 by Robey Pointer
code style changes
3323
                self.outf.write(c.user_email() + '\n')
1816.2.2 by Robey Pointer
fix 'whoami' to use encodings and allow setting the global or branch identity
3324
            else:
1816.2.10 by Robey Pointer
code style changes
3325
                self.outf.write(c.username() + '\n')
1816.2.4 by Robey Pointer
flesh out 'whoami' docs a little, and don't display the identity after setting it
3326
            return
1816.2.2 by Robey Pointer
fix 'whoami' to use encodings and allow setting the global or branch identity
3327
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
3328
        # display a warning if an email address isn't included in the given name.
3329
        try:
3330
            config.extract_email_address(name)
2055.2.2 by John Arbash Meinel
Switch extract_email_address() to use a more specific exception
3331
        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
3332
            warning('"%s" does not seem to contain an email address.  '
3333
                    'This is allowed, but not recommended.', name)
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3334
1816.2.4 by Robey Pointer
flesh out 'whoami' docs a little, and don't display the identity after setting it
3335
        # use global config unless --branch given
3336
        if branch:
5171.3.15 by Martin von Gagern
Add --directory option to whoami.
3337
            if directory is None:
3338
                c = Branch.open_containing(u'.')[0].get_config()
3339
            else:
3340
                c = Branch.open(directory).get_config()
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3341
        else:
1816.2.4 by Robey Pointer
flesh out 'whoami' docs a little, and don't display the identity after setting it
3342
            c = config.GlobalConfig()
3343
        c.set_user_option('email', name)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3344
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.
3345
1185.35.14 by Aaron Bentley
Implemented nick command
3346
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
3347
    __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,
3348
3349
    If unset, the tree root directory name is used as the nickname.
3350
    To print the current nickname, execute with no argument.
3351
3352
    Bound branches use the nickname of its master branch unless it is set
3353
    locally.
1185.35.14 by Aaron Bentley
Implemented nick command
3354
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3355
3356
    _see_also = ['info']
1185.35.14 by Aaron Bentley
Implemented nick command
3357
    takes_args = ['nickname?']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
3358
    takes_options = ['directory']
3359
    def run(self, nickname=None, directory=u'.'):
3360
        branch = Branch.open_containing(directory)[0]
1185.35.14 by Aaron Bentley
Implemented nick command
3361
        if nickname is None:
3362
            self.printme(branch)
3363
        else:
3364
            branch.nick = nickname
3365
3366
    @display_command
3367
    def printme(self, branch):
4988.8.4 by Vincent Ladeuil
Fix lines too long, fix inverted assertions.
3368
        self.outf.write('%s\n' % branch.nick)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3369
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.
3370
2900.3.2 by Tim Penhey
A working alias command.
3371
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
3372
    __doc__ = """Set/unset and display aliases.
2900.3.2 by Tim Penhey
A working alias command.
3373
3374
    :Examples:
3375
        Show the current aliases::
3376
3377
            bzr alias
3378
3379
        Show the alias specified for 'll'::
3380
3381
            bzr alias ll
3382
3383
        Set an alias for 'll'::
3384
2900.3.10 by Tim Penhey
Show examples, and change text to use double rather than single quotes.
3385
            bzr alias ll="log --line -r-10..-1"
2900.3.2 by Tim Penhey
A working alias command.
3386
2900.3.4 by Tim Penhey
Removed the unalais separate command.
3387
        To remove an alias for 'll'::
3388
3389
            bzr alias --remove ll
3390
2900.3.2 by Tim Penhey
A working alias command.
3391
    """
3392
    takes_args = ['name?']
2900.3.4 by Tim Penhey
Removed the unalais separate command.
3393
    takes_options = [
3394
        Option('remove', help='Remove the alias.'),
3395
        ]
2900.3.2 by Tim Penhey
A working alias command.
3396
2900.3.4 by Tim Penhey
Removed the unalais separate command.
3397
    def run(self, name=None, remove=False):
3398
        if remove:
3399
            self.remove_alias(name)
3400
        elif name is None:
2900.3.2 by Tim Penhey
A working alias command.
3401
            self.print_aliases()
3402
        else:
3403
            equal_pos = name.find('=')
3404
            if equal_pos == -1:
3405
                self.print_alias(name)
3406
            else:
3407
                self.set_alias(name[:equal_pos], name[equal_pos+1:])
3408
2900.3.4 by Tim Penhey
Removed the unalais separate command.
3409
    def remove_alias(self, alias_name):
3410
        if alias_name is None:
3411
            raise errors.BzrCommandError(
3412
                'bzr alias --remove expects an alias to remove.')
3413
        # If alias is not found, print something like:
3414
        # unalias: foo: not found
2900.3.8 by Tim Penhey
Use the exception text for unalias not found.
3415
        c = config.GlobalConfig()
3416
        c.unset_alias(alias_name)
2900.3.4 by Tim Penhey
Removed the unalais separate command.
3417
3418
    @display_command
2900.3.2 by Tim Penhey
A working alias command.
3419
    def print_aliases(self):
3420
        """Print out the defined aliases in a similar format to bash."""
3421
        aliases = config.GlobalConfig().get_aliases()
2900.3.7 by Tim Penhey
Updates from Aaron's review.
3422
        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.
3423
            self.outf.write('bzr alias %s="%s"\n' % (key, value))
2900.3.2 by Tim Penhey
A working alias command.
3424
3425
    @display_command
3426
    def print_alias(self, alias_name):
3427
        from bzrlib.commands import get_alias
3428
        alias = get_alias(alias_name)
3429
        if alias is None:
2900.3.7 by Tim Penhey
Updates from Aaron's review.
3430
            self.outf.write("bzr alias: %s: not found\n" % alias_name)
2900.3.2 by Tim Penhey
A working alias command.
3431
        else:
2900.3.7 by Tim Penhey
Updates from Aaron's review.
3432
            self.outf.write(
2900.3.11 by Tim Penhey
Fixed the output in the tests.
3433
                'bzr alias %s="%s"\n' % (alias_name, ' '.join(alias)))
2900.3.2 by Tim Penhey
A working alias command.
3434
2900.3.12 by Tim Penhey
Final review comments.
3435
    def set_alias(self, alias_name, alias_command):
2900.3.2 by Tim Penhey
A working alias command.
3436
        """Save the alias in the global config."""
3437
        c = config.GlobalConfig()
2900.3.12 by Tim Penhey
Final review comments.
3438
        c.set_alias(alias_name, alias_command)
2900.3.2 by Tim Penhey
A working alias command.
3439
3440
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3441
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
3442
    __doc__ = """Run internal test suite.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3443
2213.2.1 by Martin Pool
Add selftest --first flag
3444
    If arguments are given, they are regular expressions that say which tests
3445
    should run.  Tests matching any expression are run, and other tests are
3446
    not run.
3447
3448
    Alternatively if --first is given, matching tests are run first and then
3449
    all other tests are run.  This is useful if you have been working in a
3450
    particular area, but want to make sure nothing else was broken.
1552 by Martin Pool
Improved help text for bzr selftest
3451
2394.2.2 by Ian Clatworthy
Add --randomize and update help
3452
    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
3453
    excluded, regardless of whether they match --first or not.
2394.2.2 by Ian Clatworthy
Add --randomize and update help
3454
3455
    To help catch accidential dependencies between tests, the --randomize
3456
    option is useful. In most cases, the argument used is the word 'now'.
3457
    Note that the seed used for the random number generator is displayed
3458
    when this option is used. The seed can be explicitly passed as the
3459
    argument to this option if required. This enables reproduction of the
3460
    actual ordering used if and when an order sensitive problem is encountered.
3461
3462
    If --list-only is given, the tests that would be run are listed. This is
3463
    useful when combined with --first, --exclude and/or --randomize to
3464
    understand their impact. The test harness reports "Listed nn tests in ..."
3465
    instead of "Ran nn tests in ..." when list mode is enabled.
3466
1552 by Martin Pool
Improved help text for bzr selftest
3467
    If the global option '--no-plugins' is given, plugins are not loaded
3468
    before running the selftests.  This has two effects: features provided or
3469
    modified by plugins will not be tested, and tests provided by plugins will
3470
    not be run.
3471
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3472
    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)
3473
    typically inside $TMPDIR or /tmp.
3474
4685.1.2 by Robert Collins
Document BZR_TEST_PDB in cmd_selftest's help.
3475
    If you set BZR_TEST_PDB=1 when running selftest, failing tests will drop
3476
    into a pdb postmortem session.
3477
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
3478
    :Examples:
3479
        Run only tests relating to 'ignore'::
3480
3481
            bzr selftest ignore
3482
3483
        Disable plugins and list tests as they're run::
3484
3485
            bzr --no-plugins selftest -v
1185.16.58 by mbp at sourcefrog
- run all selftests by default
3486
    """
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.
3487
    # NB: this is used from the class without creating an instance, which is
3488
    # why it does not have a self parameter.
3489
    def get_transport_type(typestring):
3490
        """Parse and return a transport specifier."""
3491
        if typestring == "sftp":
4797.11.2 by Vincent Ladeuil
Stop requiring testtools for sftp use.
3492
            from bzrlib.tests import stub_sftp
3493
            return stub_sftp.SFTPAbsoluteServer
1534.4.26 by Robert Collins
Move working tree initialisation out from Branch.initialize, deprecated Branch.initialize to Branch.create.
3494
        if typestring == "memory":
5017.3.36 by Vincent Ladeuil
-s bb.test_selftest passing
3495
            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.
3496
            return memory.MemoryServer
1558.10.1 by Aaron Bentley
Handle lockdirs over NFS properly
3497
        if typestring == "fakenfs":
5017.3.36 by Vincent Ladeuil
-s bb.test_selftest passing
3498
            from bzrlib.tests import test_server
3499
            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.
3500
        msg = "No known transport type %s. Supported types are: sftp\n" %\
3501
            (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
3502
        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.
3503
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3504
    hidden = True
1185.1.57 by Robert Collins
nuke --pattern to selftest, replace with regexp.search calls.
3505
    takes_args = ['testspecs*']
1552 by Martin Pool
Improved help text for bzr selftest
3506
    takes_options = ['verbose',
2418.2.2 by Martin Pool
Add -1 option to selftest
3507
                     Option('one',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3508
                             help='Stop when one test fails.',
2418.2.2 by Martin Pool
Add -1 option to selftest
3509
                             short_name='1',
3510
                             ),
2333.1.1 by Dmitry Vasiliev
Fixed typo and removed some trailing whitespaces
3511
                     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.
3512
                            help='Use a different transport by default '
3513
                                 'throughout the test suite.',
3514
                            type=get_transport_type),
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3515
                     Option('benchmark',
5050.10.1 by Martin Pool
Remove bzr selftest --benchmark
3516
                            help='Run the benchmarks rather than selftests.',
3517
                            hidden=True),
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
3518
                     Option('lsprof-timed',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3519
                            help='Generate lsprof output for benchmarked'
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
3520
                                 ' sections of code.'),
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
3521
                     Option('lsprof-tests',
3522
                            help='Generate lsprof output for each test.'),
2213.2.1 by Martin Pool
Add selftest --first flag
3523
                     Option('first',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3524
                            help='Run all tests, but run specified tests first.',
2418.2.1 by Martin Pool
Add -f alias for selftest --first
3525
                            short_name='f',
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
3526
                            ),
2394.2.1 by Ian Clatworthy
--list and --exclude first cut
3527
                     Option('list-only',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3528
                            help='List the tests instead of running them.'),
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3529
                     RegistryOption('parallel',
4205.3.5 by Robert Collins
Missing . on the parallel option.
3530
                        help="Run the test suite in parallel.",
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3531
                        lazy_registry=('bzrlib.tests', 'parallel_registry'),
3532
                        value_switches=False,
3533
                        ),
2394.2.2 by Ian Clatworthy
Add --randomize and update help
3534
                     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
3535
                            help='Randomize the order of tests using the given'
3536
                                 ' seed or "now" for the current time.'),
2394.2.2 by Ian Clatworthy
Add --randomize and update help
3537
                     Option('exclude', type=str, argname="PATTERN",
2394.2.6 by Ian Clatworthy
completed blackbox tests
3538
                            short_name='x',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
3539
                            help='Exclude tests that match this regular'
3540
                                 ' expression.'),
4165.1.1 by Robert Collins
Add builtin subunit support.
3541
                     Option('subunit',
3542
                        help='Output test progress via subunit.'),
2658.3.3 by Daniel Watkins
Added UI support for bzr selftest --strict.
3543
                     Option('strict', help='Fail on missing dependencies or '
3544
                            'known failures.'),
3193.1.8 by Vincent Ladeuil
Add '--load-list' option to selftest.
3545
                     Option('load-list', type=str, argname='TESTLISTFILE',
3546
                            help='Load a test id list from a text file.'),
3390.1.1 by Andrew Bennetts
Add --debugflags/-E option to selftest.
3547
                     ListOption('debugflag', type=str, short_name='E',
3548
                                help='Turn on a selftest debug flag.'),
3649.6.4 by Vincent Ladeuil
selftest --starting-with now accepts multiple values.
3549
                     ListOption('starting-with', type=str, argname='TESTID',
3550
                                param_name='starting_with', short_name='s',
3551
                                help=
3552
                                'Load only the tests starting with TESTID.'),
1725.1.1 by Robert Collins
'bzr selftest --benchmark --lsprof-timed' will use lsprofile to generate
3553
                     ]
2204.3.4 by Alexander Belchenko
Command 'selftest' use 'replace' encoding_type to prevent sudden traceback
3554
    encoding_type = 'replace'
1185.16.58 by mbp at sourcefrog
- run all selftests by default
3555
4000.2.3 by Robert Collins
Allow extra options to bzrlib.tests.selftest from plugins.
3556
    def __init__(self):
3557
        Command.__init__(self)
3558
        self.additional_selftest_args = {}
3559
2805.1.1 by Ian Clatworthy
Fix selftest --benchmark so verbose by default again
3560
    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)
3561
            transport=None, benchmark=None,
5050.10.3 by Martin Pool
Delete obsolete selftest --cache-dir option
3562
            lsprof_timed=None,
2598.4.1 by Martin Pool
Remove obsolete --clean-output, --keep-output, --numbered-dirs selftest options (thanks Alexander)
3563
            first=False, list_only=False,
3198.1.1 by Vincent Ladeuil
Add --load-list option to selftest
3564
            randomize=None, exclude=None, strict=False,
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3565
            load_list=None, debugflag=None, starting_with=None, subunit=False,
4641.3.3 by Robert Collins
Enable --lsprof-tests on bzr selftest.
3566
            parallel=None, lsprof_tests=False):
1707.2.2 by Robert Collins
Start on bench_add, an add benchtest.
3567
        from bzrlib.tests import selftest
2321.2.1 by Alexander Belchenko
`bzr selftest --numbered-dirs` use numbered dirs for TestCaseInTempDir
3568
3427.5.3 by John Arbash Meinel
Update the activate_deprecation_warnings so it can be skipped if there is already an error set.
3569
        # Make deprecation warnings visible, unless -Werror is set
3427.5.7 by John Arbash Meinel
Bring back always in the form of 'override'.
3570
        symbol_versioning.activate_deprecation_warnings(override=False)
3427.5.3 by John Arbash Meinel
Update the activate_deprecation_warnings so it can be skipped if there is already an error set.
3571
2095.4.1 by Martin Pool
Better progress bars during tests
3572
        if testspecs_list is not None:
3573
            pattern = '|'.join(testspecs_list)
3574
        else:
3575
            pattern = ".*"
4165.1.1 by Robert Collins
Add builtin subunit support.
3576
        if subunit:
4165.1.2 by Robert Collins
Make a clear error when attempting to use subunit and it is not available.
3577
            try:
3578
                from bzrlib.tests import SubUnitBzrRunner
3579
            except ImportError:
3580
                raise errors.BzrCommandError("subunit not available. subunit "
3581
                    "needs to be installed to use --subunit.")
4165.1.1 by Robert Collins
Add builtin subunit support.
3582
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
5229.1.8 by Vincent Ladeuil
Subunit stream handling.
3583
            # On Windows, disable automatic conversion of '\n' to '\r\n' in
3584
            # stdout, which would corrupt the subunit stream. 
5229.2.2 by Vincent Ladeuil
More robust stream checking for subunit on windows
3585
            # FIXME: This has been fixed in subunit trunk (>0.0.5) so the
3586
            # following code can be deleted when it's sufficiently deployed
3587
            # -- vila/mgz 20100514
3588
            if (sys.platform == "win32"
3589
                and getattr(sys.stdout, 'fileno', None) is not None):
5229.1.8 by Vincent Ladeuil
Subunit stream handling.
3590
                import msvcrt
3591
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
4205.3.2 by Robert Collins
Create fork and reinvoke parallel testing support.
3592
        if parallel:
3593
            self.additional_selftest_args.setdefault(
3594
                'suite_decorators', []).append(parallel)
2095.4.1 by Martin Pool
Better progress bars during tests
3595
        if benchmark:
5050.10.1 by Martin Pool
Remove bzr selftest --benchmark
3596
            raise errors.BzrCommandError(
3597
                "--benchmark is no longer supported from bzr 2.2; "
3598
                "use bzr-usertest instead")
3599
        test_suite_factory = 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.
3600
        selftest_kwargs = {"verbose": verbose,
3601
                          "pattern": pattern,
3602
                          "stop_on_failure": one,
3603
                          "transport": transport,
3604
                          "test_suite_factory": test_suite_factory,
3605
                          "lsprof_timed": lsprof_timed,
3606
                          "lsprof_tests": lsprof_tests,
3607
                          "matching_tests_first": first,
3608
                          "list_only": list_only,
3609
                          "random_seed": randomize,
3610
                          "exclude_pattern": exclude,
3611
                          "strict": strict,
3612
                          "load_list": load_list,
3613
                          "debug_flags": debugflag,
3614
                          "starting_with": starting_with
3615
                          }
3616
        selftest_kwargs.update(self.additional_selftest_args)
3617
        result = selftest(**selftest_kwargs)
2095.4.1 by Martin Pool
Better progress bars during tests
3618
        return int(not result)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3619
3620
3621
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
3622
    __doc__ = """Show version of bzr."""
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
3623
2785.1.2 by bialix at ukr
bugfix for #131100
3624
    encoding_type = 'replace'
3346.2.1 by Martin Pool
Add version --short option
3625
    takes_options = [
3626
        Option("short", help="Print just the version number."),
3627
        ]
2785.1.2 by bialix at ukr
bugfix for #131100
3628
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
3629
    @display_command
3346.2.1 by Martin Pool
Add version --short option
3630
    def run(self, short=False):
1819.1.8 by Martin Pool
Improved reporting of bzrlib revision_id
3631
        from bzrlib.version import show_version
3346.2.1 by Martin Pool
Add version --short option
3632
        if short:
3346.2.7 by Martin Pool
Commands should use self.outf not print
3633
            self.outf.write(bzrlib.version_string + '\n')
3346.2.1 by Martin Pool
Add version --short option
3634
        else:
3635
            show_version(to_file=self.outf)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3636
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
3637
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3638
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
3639
    __doc__ = """Statement of optimism."""
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
3640
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3641
    hidden = True
1871.1.1 by Robert Collins
Relocate bzrlib selftest external output tests to bzrlib/tests/blackbox/test_selftest.py.
3642
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
3643
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3644
    def run(self):
4988.8.3 by Ed Bayiates Home
More builtin command UIFactory updates
3645
        self.outf.write("It sure does!\n")
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3646
3647
3648
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
3649
    __doc__ = """Find and print a base revision for merging two branches."""
1185.16.3 by Martin Pool
- remove all TODOs from bzr help messages
3650
    # TODO: Options to specify revisions on either side, as if
3651
    #       merging only part of the history.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3652
    takes_args = ['branch', 'other']
3653
    hidden = True
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3654
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
3655
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3656
    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.
3657
        from bzrlib.revision import ensure_null
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3658
1442.1.64 by Robert Collins
Branch.open_containing now returns a tuple (Branch, relative-path).
3659
        branch1 = Branch.open_containing(branch)[0]
3660
        branch2 = Branch.open_containing(other)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
3661
        self.add_cleanup(branch1.lock_read().unlock)
3662
        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.
3663
        last1 = ensure_null(branch1.last_revision())
3664
        last2 = ensure_null(branch2.last_revision())
3665
3666
        graph = branch1.repository.get_graph(branch2.repository)
3667
        base_rev_id = graph.find_unique_lca(last1, last2)
3668
4988.8.3 by Ed Bayiates Home
More builtin command UIFactory updates
3669
        self.outf.write('merge base is revision %s\n' % base_rev_id)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3670
3671
3672
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
3673
    __doc__ = """Perform a three-way merge.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3674
3277.1.1 by Peter Schuller
Document the relationship between bzr send and bzr merge. In
3675
    The source of the merge can be specified either in the form of a branch,
3676
    or in the form of a path to a file containing a merge directive generated
3677
    with bzr send. If neither is specified, the default is the upstream branch
3277.1.2 by Peter Schuller
As per feedback to previous attempt:
3678
    or the branch most recently merged using --remember.
3277.1.1 by Peter Schuller
Document the relationship between bzr send and bzr merge. In
3679
3277.1.2 by Peter Schuller
As per feedback to previous attempt:
3680
    When merging a branch, by default the tip will be merged. To pick a different
3681
    revision, pass --revision. If you specify two values, the first will be used as
3313.1.1 by Ian Clatworthy
Improve doc on send/merge relationship (Peter Schuller)
3682
    BASE and the second one as OTHER. Merging individual revisions, or a subset of
3683
    available revisions, like this is commonly referred to as "cherrypicking".
3277.1.3 by Peter Schuller
Identify by name the "cherrypicking" mode of operation of 'bzr merge'.
3684
3685
    Revision numbers are always relative to the branch being merged.
1172 by Martin Pool
- better explanation when merge fails with AmbiguousBase
3686
1551.2.19 by Aaron Bentley
Added See Conflicts to merge help
3687
    By default, bzr will try to merge in all new work from the other
1172 by Martin Pool
- better explanation when merge fails with AmbiguousBase
3688
    branch, automatically determining an appropriate base.  If this
3689
    fails, you may need to give an explicit base.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3690
1551.2.18 by Aaron Bentley
Updated docs to clarify conflict handling
3691
    Merge will do its best to combine the changes in two branches, but there
3692
    are some kinds of problems only a human can fix.  When it encounters those,
3693
    it will mark a conflict.  A conflict means that you need to fix something,
3694
    before you should commit.
3695
1551.2.19 by Aaron Bentley
Added See Conflicts to merge help
3696
    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
3697
1614.2.4 by Olaf Conradi
Renamed argument location in command merge back to branch.
3698
    If there is no default branch set, the first merge will set it. After
3699
    that, you can omit the branch to use the default.  To change the
1785.1.4 by John Arbash Meinel
Update help for the new --remember semantics.
3700
    default, use --remember. The value will only be saved if the remote
3701
    location can be accessed.
1614.2.2 by Olaf Conradi
Merge command:
3702
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
3703
    The results of the merge are placed into the destination working
3704
    directory, where they can be reviewed (with bzr diff), tested, and then
3705
    committed to record the result of the merge.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
3706
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3707
    merge refuses to run if there are any uncommitted changes, unless
4978.1.1 by Vincent Ladeuil
Add documentation for multi-parent merges
3708
    --force is given. The --force option can also be used to create a
4971.3.2 by Neil Martinsen-Burrell
reformat examples with less reST
3709
    merge revision which has more than two parents.
4955.3.2 by Vincent Ladeuil
Tweak the spacing.
3710
3711
    If one would like to merge changes from the working tree of the other
3712
    branch without merging any committed revisions, the --uncommitted option
3713
    can be given.
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
3714
4526.6.15 by Aaron Bentley
Update command help
3715
    To select only some changes to merge, use "merge -i", which will prompt
3716
    you to apply each diff hunk and file change, similar to "shelve".
3717
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
3718
    :Examples:
3719
        To merge the latest revision from bzr.dev::
3720
3721
            bzr merge ../bzr.dev
3722
3723
        To merge changes up to and including revision 82 from bzr.dev::
3724
3725
            bzr merge -r 82 ../bzr.dev
3726
3727
        To merge the changes introduced by 82, without previous changes::
3728
3729
            bzr merge -r 81..82 ../bzr.dev
3277.1.1 by Peter Schuller
Document the relationship between bzr send and bzr merge. In
3730
4816.1.1 by Ian Clatworthy
Trivial formatting fix to merge help
3731
        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
3732
3733
            bzr merge /tmp/merge
4971.3.2 by Neil Martinsen-Burrell
reformat examples with less reST
3734
3735
        To create a merge revision with three parents from two branches
4971.3.3 by Vincent Ladeuil
Tweak NEWS entry order and some cleanup.
3736
        feature1a and feature1b:
4971.3.2 by Neil Martinsen-Burrell
reformat examples with less reST
3737
3738
            bzr merge ../feature1a
3739
            bzr merge ../feature1b --force
3740
            bzr commit -m 'revision with three parents'
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3741
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
3742
3008.1.25 by Aaron Bentley
Set encoding exact on cmd_merge
3743
    encoding_type = 'exact'
4095.2.1 by Neil Martinsen-Burrell
Better help for bzr send
3744
    _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.
3745
    takes_args = ['location?']
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
3746
    takes_options = [
2839.5.1 by Alexander Belchenko
add -c option to merge command
3747
        'change',
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
3748
        'revision',
3749
        Option('force',
3750
               help='Merge even if the destination tree has uncommitted changes.'),
3751
        'merge-type',
3752
        'reprocess',
3753
        'remember',
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
3754
        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
3755
               "conflicts."),
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
3756
        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
3757
               ' from a working copy, instead of branch changes.'),
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
3758
        Option('pull', help='If the destination is already'
3759
                ' 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
3760
                ' source rather than merging.  When this happens,'
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
3761
                ' you do not need to commit the result.'),
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
3762
        custom_help('directory',
2598.1.10 by Martin Pool
Clean up options that are registered globally and used once or not at all.
3763
               help='Branch to merge into, '
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
3764
                    'rather than the one containing the working directory.'),
4526.6.3 by Aaron Bentley
Implement interactive merging.
3765
        Option('preview', help='Instead of merging, show a diff of the'
3766
               ' merge.'),
3767
        Option('interactive', help='Select changes interactively.',
3768
            short_name='i')
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
3769
    ]
1551.6.22 by Aaron Bentley
Improved help for remerge and merge
3770
3277.1.4 by Peter Schuller
As per further feedback, use LOCATION instead of MERGE_OR_MERGE_DIRECTIVE.
3771
    def run(self, location=None, revision=None, force=False,
3744.2.1 by John Arbash Meinel
Change 'bzr merge' so that it uses --reprocess as long as --show-base is not given.
3772
            merge_type=None, show_base=False, reprocess=None, remember=False,
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
3773
            uncommitted=False, pull=False,
3774
            directory=None,
3008.1.24 by Aaron Bentley
Add merge --preview to show diff
3775
            preview=False,
4526.6.3 by Aaron Bentley
Implement interactive merging.
3776
            interactive=False,
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
3777
            ):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3778
        if merge_type is None:
1996.3.5 by John Arbash Meinel
Cleanup, deprecated, and get the tests passing again.
3779
            merge_type = _mod_merge.Merge3Merger
1614.2.2 by Olaf Conradi
Merge command:
3780
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
3781
        if directory is None: directory = u'.'
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3782
        possible_transports = []
3783
        merger = None
3784
        allow_pending = True
3785
        verified = 'inapplicable'
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
3786
        tree = WorkingTree.open_containing(directory)[0]
4037.2.1 by Roberto Aguilar
Check for umcommitted changes.
3787
4037.2.2 by Roberto Aguilar
Updating uncommitted changes check.
3788
        try:
3789
            basis_tree = tree.revision_tree(tree.last_revision())
3790
        except errors.NoSuchRevision:
3791
            basis_tree = tree.basis_tree()
4672.3.2 by Vincent Ladeuil
Don't allow merge on top of pending merges without --force.
3792
3793
        # 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
3794
        if not force:
4721.3.2 by Vincent Ladeuil
Simplify mutable_tree.has_changes() and update call sites.
3795
            if tree.has_changes():
4104.8.1 by Robert Collins
Cherrypick the fix for merge --force onto 1.13.1
3796
                raise errors.UncommittedChanges(tree)
4037.2.1 by Roberto Aguilar
Check for umcommitted changes.
3797
3586.1.31 by Ian Clatworthy
view filtering for pull, update & merge
3798
        view_info = _get_view_info_for_change_reporter(tree)
1551.10.25 by Aaron Bentley
Make ChangeReporter private
3799
        change_reporter = delta._ChangeReporter(
3586.1.31 by Ian Clatworthy
view filtering for pull, update & merge
3800
            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.
3801
        pb = ui.ui_factory.nested_progress_bar()
3802
        self.add_cleanup(pb.finished)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
3803
        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.
3804
        if location is not None:
3805
            try:
3806
                mergeable = bundle.read_mergeable_from_url(location,
3807
                    possible_transports=possible_transports)
3808
            except errors.NotABundle:
3809
                mergeable = None
3810
            else:
3811
                if uncommitted:
3812
                    raise errors.BzrCommandError('Cannot use --uncommitted'
3813
                        ' with bundles or merge directives.')
3814
3815
                if revision is not None:
3816
                    raise errors.BzrCommandError(
3817
                        'Cannot use -r with merge directives or bundles')
3818
                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
3819
                   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.
3820
3821
        if merger is None and uncommitted:
3822
            if revision is not None and len(revision) > 0:
3823
                raise errors.BzrCommandError('Cannot use --uncommitted and'
3824
                    ' --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
3825
            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.
3826
            allow_pending = False
3827
3828
        if merger is None:
3829
            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
3830
                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.
3831
3832
        merger.merge_type = merge_type
3833
        merger.reprocess = reprocess
3834
        merger.show_base = show_base
3835
        self.sanity_check_merger(merger)
3836
        if (merger.base_rev_id == merger.other_rev_id and
3837
            merger.other_rev_id is not None):
3838
            note('Nothing to do.')
3839
            return 0
3840
        if pull:
3841
            if merger.interesting_files is not None:
3842
                raise errors.BzrCommandError('Cannot pull individual files')
3843
            if (merger.base_rev_id == tree.last_revision()):
3844
                result = tree.pull(merger.other_branch, False,
3845
                                   merger.other_rev_id)
3846
                result.report(self.outf)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3847
                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.
3848
        if merger.this_basis is None:
3849
            raise errors.BzrCommandError(
3850
                "This branch has no commits."
3851
                " (perhaps you would prefer 'bzr pull')")
3852
        if preview:
3853
            return self._do_preview(merger)
3854
        elif interactive:
3855
            return self._do_interactive(merger)
3856
        else:
3857
            return self._do_merge(merger, change_reporter, allow_pending,
3858
                                  verified)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3859
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.
3860
    def _get_preview(self, merger):
3008.1.24 by Aaron Bentley
Add merge --preview to show diff
3861
        tree_merger = merger.make_merger()
3862
        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.
3863
        self.add_cleanup(tt.finalize)
4526.6.3 by Aaron Bentley
Implement interactive merging.
3864
        result_tree = tt.get_preview_tree()
4526.6.8 by Aaron Bentley
Remove unused tt parameter.
3865
        return result_tree
4526.6.3 by Aaron Bentley
Implement interactive merging.
3866
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.
3867
    def _do_preview(self, merger):
4526.6.3 by Aaron Bentley
Implement interactive merging.
3868
        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.
3869
        result_tree = self._get_preview(merger)
4797.57.10 by Alexander Belchenko
path_encoding selection logic extracted as helper function
3870
        path_encoding = osutils.get_diff_header_encoding()
4526.6.3 by Aaron Bentley
Implement interactive merging.
3871
        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.
3872
                        old_label='', new_label='',
3873
                        path_encoding=path_encoding)
3008.1.24 by Aaron Bentley
Add merge --preview to show diff
3874
3875
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
3876
        merger.change_reporter = change_reporter
3877
        conflict_count = merger.do_merge()
3878
        if allow_pending:
3879
            merger.set_pending()
3880
        if verified == 'failed':
3881
            warning('Preview patch does not match changes')
3882
        if conflict_count != 0:
3883
            return 1
3884
        else:
3885
            return 0
3886
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.
3887
    def _do_interactive(self, merger):
4526.6.13 by Aaron Bentley
Add docstring to do_interactive.
3888
        """Perform an interactive merge.
3889
3890
        This works by generating a preview tree of the merge, then using
3891
        Shelver to selectively remove the differences between the working tree
3892
        and the preview tree.
3893
        """
4526.6.4 by Aaron Bentley
Remove changes_destroyed message.
3894
        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.
3895
        result_tree = self._get_preview(merger)
4526.6.14 by Aaron Bentley
Use default DiffWriter.
3896
        writer = bzrlib.option.diff_writer_registry.get()
4526.6.4 by Aaron Bentley
Remove changes_destroyed message.
3897
        shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
4526.6.14 by Aaron Bentley
Use default DiffWriter.
3898
                                   reporter=shelf_ui.ApplyReporter(),
3899
                                   diff_writer=writer(sys.stdout))
4832.2.1 by Aaron Bentley
Ensure merge -i doesn't leave branch write_locked.
3900
        try:
3901
            shelver.run()
3902
        finally:
3903
            shelver.finalize()
4526.6.3 by Aaron Bentley
Implement interactive merging.
3904
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3905
    def sanity_check_merger(self, merger):
3906
        if (merger.show_base and
3907
            not merger.merge_type is _mod_merge.Merge3Merger):
3908
            raise errors.BzrCommandError("Show-base is not supported for this"
2665.2.1 by Michael Hudson
test and fix for a NameError in merge --weave --show-base
3909
                                         " 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.
3910
        if merger.reprocess is None:
3911
            if merger.show_base:
3912
                merger.reprocess = False
3913
            else:
3914
                # Use reprocess if the merger supports it
3915
                merger.reprocess = merger.merge_type.supports_reprocess
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3916
        if merger.reprocess and not merger.merge_type.supports_reprocess:
3917
            raise errors.BzrCommandError("Conflict reduction is not supported"
2665.2.1 by Michael Hudson
test and fix for a NameError in merge --weave --show-base
3918
                                         " for merge type %s." %
3919
                                         merger.merge_type)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3920
        if merger.reprocess and merger.show_base:
3921
            raise errors.BzrCommandError("Cannot do conflict reduction and"
3922
                                         " show base.")
3923
1551.15.75 by Aaron Bentley
_merger_from_branch -> _get_merger_from_branch
3924
    def _get_merger_from_branch(self, tree, location, revision, remember,
3925
                                possible_transports, pb):
3926
        """Produce a merger from a location, assuming it refers to a branch."""
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3927
        from bzrlib.tag import _merge_tags_if_possible
3928
        # find the branch locations
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
3929
        other_loc, user_location = self._select_branch_location(tree, location,
1551.15.74 by Aaron Bentley
Textual updates from review
3930
            revision, -1)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3931
        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
3932
            base_loc, _unused = self._select_branch_location(tree,
3933
                location, revision, 0)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3934
        else:
3935
            base_loc = other_loc
3936
        # Open the branches
3937
        other_branch, other_path = Branch.open_containing(other_loc,
3938
            possible_transports)
3939
        if base_loc == other_loc:
3940
            base_branch = other_branch
3941
        else:
3942
            base_branch, base_path = Branch.open_containing(base_loc,
1551.15.66 by Aaron Bentley
Improve behavior with revision ids
3943
                possible_transports)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3944
        # Find the revision ids
4435.1.4 by Aaron Bentley
Fix tabs.
3945
        other_revision_id = None
3946
        base_revision_id = None
3947
        if revision is not None:
3948
            if len(revision) >= 1:
3949
                other_revision_id = revision[-1].as_revision_id(other_branch)
3950
            if len(revision) == 2:
3951
                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.
3952
        if other_revision_id is None:
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3953
            other_revision_id = _mod_revision.ensure_null(
3954
                other_branch.last_revision())
2485.8.37 by Vincent Ladeuil
Fix merge multiple connections. Test suite *not* passing (sftp
3955
        # Remember where we merge from
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
3956
        if ((remember or tree.branch.get_submit_branch() is None) and
3957
             user_location is not None):
3958
            tree.branch.set_submit_branch(other_branch.base)
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3959
        _merge_tags_if_possible(other_branch, tree.branch)
3960
        merger = _mod_merge.Merger.from_revision_ids(pb, tree,
3961
            other_revision_id, base_revision_id, other_branch, base_branch)
3962
        if other_path != '':
3963
            allow_pending = False
3964
            merger.interesting_files = [other_path]
1645.1.1 by Aaron Bentley
Implement single-file merge
3965
        else:
1551.15.67 by Aaron Bentley
Stop using _merge_helper for merging
3966
            allow_pending = True
3967
        return merger, allow_pending
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
3968
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.
3969
    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.
3970
        """Get a merger for uncommitted changes.
3971
3972
        :param tree: The tree the merger should apply to.
3973
        :param location: The location containing uncommitted changes.
3974
        :param pb: The progress bar to use for showing progress.
3975
        """
3976
        location = self._select_branch_location(tree, location)[0]
3977
        other_tree, other_path = WorkingTree.open_containing(location)
3978
        merger = _mod_merge.Merger.from_uncommitted(tree, other_tree, pb)
3979
        if other_path != '':
3980
            merger.interesting_files = [other_path]
3981
        return merger
3982
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
3983
    def _select_branch_location(self, tree, user_location, revision=None,
1551.15.74 by Aaron Bentley
Textual updates from review
3984
                                index=None):
3985
        """Select a branch location, according to possible inputs.
3986
3987
        If provided, branches from ``revision`` are preferred.  (Both
3988
        ``revision`` and ``index`` must be supplied.)
3989
3990
        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
3991
        ``submit`` or ``parent`` location is used, and a note is printed.
1551.15.74 by Aaron Bentley
Textual updates from review
3992
3993
        :param tree: The working tree to select a branch for merging into
3994
        :param location: The location entered by the user
3995
        :param revision: The revision parameter to the command
3996
        :param index: The index to use for the revision parameter.  Negative
3997
            indices are permitted.
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
3998
        :return: (selected_location, user_location).  The default location
3999
            will be the user-entered location.
1551.15.74 by Aaron Bentley
Textual updates from review
4000
        """
1551.15.66 by Aaron Bentley
Improve behavior with revision ids
4001
        if (revision is not None and index is not None
4002
            and revision[index] is not None):
4003
            branch = revision[index].get_branch()
4004
            if branch is not None:
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
4005
                return branch, branch
4006
        if user_location is None:
4007
            location = self._get_remembered(tree, 'Merging from')
4008
        else:
4009
            location = user_location
4010
        return location, user_location
1551.15.66 by Aaron Bentley
Improve behavior with revision ids
4011
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
4012
    def _get_remembered(self, tree, verb_string):
1685.1.59 by Martin Pool
[broken] Fix up & refactor display of remembered urls to unescape properly
4013
        """Use tree.branch's parent if none was supplied.
4014
4015
        Report if the remembered location was used.
4016
        """
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
4017
        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.
4018
        stored_location_type = "submit"
1551.20.2 by Aaron Bentley
Merge prefers submit branch, but falls back to parent branch
4019
        if stored_location is None:
4020
            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.
4021
            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
4022
        mutter("%s", stored_location)
1685.1.59 by Martin Pool
[broken] Fix up & refactor display of remembered urls to unescape properly
4023
        if stored_location is None:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
4024
            raise errors.BzrCommandError("No location specified or remembered")
3249.1.1 by Ian Clatworthy
fix merge redirection when using a remembered location
4025
        display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
3596.3.1 by James Westby
Give the user a bit more information about which saved location is being used.
4026
        note(u"%s remembered %s location %s", verb_string,
4027
                stored_location_type, display_url)
1685.1.59 by Martin Pool
[broken] Fix up & refactor display of remembered urls to unescape properly
4028
        return stored_location
4029
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4030
1185.35.4 by Aaron Bentley
Implemented remerge
4031
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
4032
    __doc__ = """Redo a merge.
1551.6.22 by Aaron Bentley
Improved help for remerge and merge
4033
4034
    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
4035
    conflicts.  Some merge techniques are better than others, and remerge
1551.6.22 by Aaron Bentley
Improved help for remerge and merge
4036
    lets you try different ones on different files.
4037
4038
    The options for remerge have the same meaning and defaults as the ones for
4039
    merge.  The difference is that remerge can (only) be run when there is a
4040
    pending merge, and it lets you specify particular files.
4041
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
4042
    :Examples:
1551.6.22 by Aaron Bentley
Improved help for remerge and merge
4043
        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
4044
        conflict regions, in addition to the usual THIS and OTHER texts::
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4045
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
4046
            bzr remerge --show-base
1551.6.22 by Aaron Bentley
Improved help for remerge and merge
4047
4048
        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
4049
        additional processing to reduce the size of conflict regions::
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4050
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
4051
            bzr remerge --merge-type weave --reprocess foobar
2374.1.1 by Ian Clatworthy
Help and man page fixes
4052
    """
1185.35.4 by Aaron Bentley
Implemented remerge
4053
    takes_args = ['file*']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
4054
    takes_options = [
4055
            'merge-type',
4056
            'reprocess',
4057
            Option('show-base',
4058
                   help="Show base revision text in conflicts."),
4059
            ]
1551.6.22 by Aaron Bentley
Improved help for remerge and merge
4060
1185.35.4 by Aaron Bentley
Implemented remerge
4061
    def run(self, file_list=None, merge_type=None, show_base=False,
4062
            reprocess=False):
5127.1.2 by Martin Pool
Lazy-load conflict commands
4063
        from bzrlib.conflicts import restore
1185.35.4 by Aaron Bentley
Implemented remerge
4064
        if merge_type is None:
1996.3.5 by John Arbash Meinel
Cleanup, deprecated, and get the tests passing again.
4065
            merge_type = _mod_merge.Merge3Merger
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
4066
        tree, file_list = WorkingTree.open_containing_paths(file_list)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4067
        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.
4068
        parents = tree.get_parent_ids()
4069
        if len(parents) != 2:
4070
            raise errors.BzrCommandError("Sorry, remerge only works after normal"
4071
                                         " merges.  Not cherrypicking or"
4072
                                         " multi-merges.")
4073
        repository = tree.branch.repository
4074
        interesting_ids = None
4075
        new_conflicts = []
4076
        conflicts = tree.conflicts()
4077
        if file_list is not None:
4078
            interesting_ids = set()
4079
            for filename in file_list:
4080
                file_id = tree.path2id(filename)
4081
                if file_id is None:
4082
                    raise errors.NotVersionedError(filename)
4083
                interesting_ids.add(file_id)
4084
                if tree.kind(file_id) != "directory":
4085
                    continue
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4086
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.
4087
                for name, ie in tree.inventory.iter_entries(file_id):
4088
                    interesting_ids.add(ie.file_id)
4089
            new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
4090
        else:
4091
            # Remerge only supports resolving contents conflicts
4092
            allowed_conflicts = ('text conflict', 'contents conflict')
4093
            restore_files = [c.path for c in conflicts
4094
                             if c.typestring in allowed_conflicts]
4095
        _mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
4096
        tree.set_conflicts(ConflictList(new_conflicts))
4097
        if file_list is not None:
4098
            restore_files = file_list
4099
        for filename in restore_files:
1551.15.47 by Aaron Bentley
Fix remerge --weave
4100
            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.
4101
                restore(tree.abspath(filename))
4102
            except errors.NotConflicted:
4103
                pass
4104
        # Disable pending merges, because the file texts we are remerging
4105
        # have not had those merges performed.  If we use the wrong parents
4106
        # list, we imply that the working tree text has seen and rejected
4107
        # all the changes from the other tree, when in fact those changes
4108
        # have not yet been seen.
4109
        tree.set_parent_ids(parents[:1])
4110
        try:
4961.2.13 by Martin Pool
Further progress bar string-pulling
4111
            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.
4112
            merger.interesting_ids = interesting_ids
4113
            merger.merge_type = merge_type
4114
            merger.show_base = show_base
4115
            merger.reprocess = reprocess
4116
            conflicts = merger.do_merge()
1185.35.4 by Aaron Bentley
Implemented remerge
4117
        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.
4118
            tree.set_parent_ids(parents)
1185.35.4 by Aaron Bentley
Implemented remerge
4119
        if conflicts > 0:
4120
            return 1
4121
        else:
4122
            return 0
4123
2023.1.1 by ghigo
add topics help
4124
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4125
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
4126
    __doc__ = """Revert files to a previous revision.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4127
1551.8.27 by Aaron Bentley
Update docs again
4128
    Giving a list of files will revert only those files.  Otherwise, all files
4129
    will be reverted.  If the revision is not specified with '--revision', the
4130
    last committed revision is used.
1551.8.26 by Aaron Bentley
Update revert help text
4131
4132
    To remove only some changes, without reverting to a prior version, use
3026.1.1 by Nicholas Allen
Fix small typo in command description for the revert command.
4133
    merge instead.  For example, "merge . --revision -2..-3" will remove the
4134
    changes introduced by -2, without affecting the changes introduced by -1.
4135
    Or to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4136
1551.8.26 by Aaron Bentley
Update revert help text
4137
    By default, any files that have been manually changed will be backed up
4138
    first.  (Files changed only by merge are not backed up.)  Backup files have
1551.8.27 by Aaron Bentley
Update docs again
4139
    '.~#~' appended to their name, where # is a number.
4140
4141
    When you provide files, you can use their current pathname or the pathname
4142
    from the target revision.  So you can use revert to "undelete" a file by
4143
    name.  If you name a directory, all the contents of that directory will be
4144
    reverted.
2614.1.1 by Martin Pool
Doc for revert, #87548
4145
4825.1.1 by Robert Collins
Merge documentation fixes from Neil Martinsen-Burrell.
4146
    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
4147
    removed.  If the files to be removed have been changed, backups will be
4148
    created as above.  Directories containing unknown files will not be
4149
    deleted.
2911.2.1 by Martin Pool
Better help for revert
4150
4955.2.1 by Neil Martinsen-Burrell
improve revert documentations discussion of pending merges
4151
    The working tree contains a list of revisions that have been merged but
4152
    not yet committed. These revisions will be included as additional parents
4153
    of the next commit.  Normally, using revert clears that list as well as
4154
    reverting the files.  If any files are specified, revert leaves the list
4155
    of uncommitted merges alone and reverts only the files.  Use ``bzr revert
4156
    .`` in the tree root to revert all files but keep the recorded merges,
4157
    and ``bzr revert --forget-merges`` to clear the pending merge list without
2911.2.1 by Martin Pool
Better help for revert
4158
    reverting any files.
4798.6.1 by Neil Martinsen-Burrell
document the use of revert --forget-merges to condense merges to a single revision
4159
4955.2.1 by Neil Martinsen-Burrell
improve revert documentations discussion of pending merges
4160
    Using "bzr revert --forget-merges", it is possible to apply all of the
4161
    changes from a branch in a single revision.  To do this, perform the merge
4162
    as desired.  Then doing revert with the "--forget-merges" option will keep
4163
    the content of the tree as it was, but it will clear the list of pending
4164
    merges.  The next commit will then contain all of the changes that are
4165
    present in the other branch, but without any other parent revisions.
4166
    Because this technique forgets where these changes originated, it may
4167
    cause additional conflicts on later merges involving the same source and
4798.6.3 by Neil Martinsen-Burrell
Add discussion of conflicts
4168
    target branches.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4169
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
4170
4171
    _see_also = ['cat', 'export']
2598.1.6 by Martin Pool
Add help for --no-backup
4172
    takes_options = [
2851.2.1 by Martin Pool
Add revert --forget-merges
4173
        'revision',
4174
        Option('no-backup', "Do not save backups of reverted files."),
4175
        Option('forget-merges',
4176
               'Remove pending merge marker, without changing any files.'),
4177
        ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4178
    takes_args = ['file*']
4179
2851.2.1 by Martin Pool
Add revert --forget-merges
4180
    def run(self, revision=None, no_backup=False, file_list=None,
4181
            forget_merges=None):
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
4182
        tree, file_list = WorkingTree.open_containing_paths(file_list)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4183
        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.
4184
        if forget_merges:
4185
            tree.set_parent_ids(tree.get_parent_ids()[:1])
4186
        else:
4187
            self._revert_tree_to_revision(tree, revision, file_list, no_backup)
2851.2.1 by Martin Pool
Add revert --forget-merges
4188
4189
    @staticmethod
4190
    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)
4191
        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
4192
        tree.revert(file_list, rev_tree, not no_backup, None,
4193
            report_changes=True)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4194
4195
4196
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
4197
    __doc__ = """Test reporting of assertion failures"""
2090.2.1 by Martin Pool
Fix some code which relies on assertions and breaks under python -O
4198
    # intended just for use in testing
4199
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4200
    hidden = True
2090.2.1 by Martin Pool
Fix some code which relies on assertions and breaks under python -O
4201
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4202
    def run(self):
2090.2.1 by Martin Pool
Fix some code which relies on assertions and breaks under python -O
4203
        raise AssertionError("always fails")
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4204
4205
4206
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
4207
    __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)
4208
    """
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4209
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
4210
    _see_also = ['topics']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
4211
    takes_options = [
4212
            Option('long', 'Show help on all commands.'),
4213
            ]
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4214
    takes_args = ['topic?']
1616.1.15 by Martin Pool
Handle 'bzr ?', etc.
4215
    aliases = ['?', '--help', '-?', '-h']
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4216
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
4217
    @display_command
3984.4.5 by Ian Clatworthy
help xxx is full help; xxx -h is concise help
4218
    def run(self, topic=None, long=False):
2023.1.1 by ghigo
add topics help
4219
        import bzrlib.help
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4220
        if topic is None and long:
4221
            topic = "commands"
3984.4.5 by Ian Clatworthy
help xxx is full help; xxx -h is concise help
4222
        bzrlib.help.help(topic)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4223
4224
4225
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
4226
    __doc__ = """Show appropriate completions for context.
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4227
2023.1.1 by ghigo
add topics help
4228
    For a list of all available commands, say 'bzr shell-complete'.
4229
    """
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4230
    takes_args = ['context?']
4231
    aliases = ['s-c']
4232
    hidden = True
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4233
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
4234
    @display_command
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4235
    def run(self, context=None):
4236
        import shellcomplete
4237
        shellcomplete.shellcomplete(context)
4238
4239
4240
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
4241
    __doc__ = """Show unmerged/unpulled revisions between two branches.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4242
2023.1.1 by ghigo
add topics help
4243
    OTHER_BRANCH may be local or remote.
3921.3.12 by Marius Kruger
add missing examples and NEWS
4244
4156.1.1 by Vincent Ladeuil
Trivial spelling correction to "bzr missing" documentation
4245
    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.
4246
    -r revision requests a specific revision, -r ..end or -r begin.. are
4247
    also valid.
4849.2.1 by Neil Martinsen-Burrell
document the return values of bzr missing
4248
            
4849.2.2 by Neil Martinsen-Burrell
better markup
4249
    :Exit values:
4849.2.1 by Neil Martinsen-Burrell
document the return values of bzr missing
4250
        1 - some missing revisions
4251
        0 - no missing revisions
3921.3.13 by Marius Kruger
update missing documentation and blackbox test to better reflect `-r 3` behaviour.
4252
3921.3.12 by Marius Kruger
add missing examples and NEWS
4253
    :Examples:
4254
4255
        Determine the missing revisions between this and the branch at the
4256
        remembered pull location::
4257
4258
            bzr missing
4259
4260
        Determine the missing revisions between this and another branch::
4261
4262
            bzr missing http://server/branch
4263
4264
        Determine the missing revisions up to a specific revision on the other
4265
        branch::
4266
4267
            bzr missing -r ..-10
4268
4269
        Determine the missing revisions up to a specific revision on this
4270
        branch::
4271
4272
            bzr missing --my-revision ..-10
2023.1.1 by ghigo
add topics help
4273
    """
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
4274
4275
    _see_also = ['merge', 'pull']
1185.54.1 by Aaron Bentley
Import Kinnison's plugin
4276
    takes_args = ['other_branch?']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
4277
    takes_options = [
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
4278
        'directory',
3921.3.6 by Marius Kruger
* fix some indentation anomalies in cmd_missing
4279
        Option('reverse', 'Reverse the order of revisions.'),
4280
        Option('mine-only',
4281
               'Display changes in the local branch only.'),
4282
        Option('this' , 'Same as --mine-only.'),
4283
        Option('theirs-only',
4284
               'Display changes in the remote branch only.'),
4285
        Option('other', 'Same as --theirs-only.'),
4286
        'log-format',
4287
        'show-ids',
4288
        'verbose',
4289
        custom_help('revision',
3921.3.11 by Marius Kruger
swap options as per review:
4290
             help='Filter on other branch revisions (inclusive). '
3921.3.6 by Marius Kruger
* fix some indentation anomalies in cmd_missing
4291
                'See "help revisionspec" for details.'),
3921.3.11 by Marius Kruger
swap options as per review:
4292
        Option('my-revision',
3921.3.6 by Marius Kruger
* fix some indentation anomalies in cmd_missing
4293
            type=_parse_revision_str,
3921.3.11 by Marius Kruger
swap options as per review:
4294
            help='Filter on local branch revisions (inclusive). '
3921.3.6 by Marius Kruger
* fix some indentation anomalies in cmd_missing
4295
                'See "help revisionspec" for details.'),
4221.1.1 by Vincent Ladeuil
Clarify 'missing --include-merges' help.
4296
        Option('include-merges',
4297
               'Show all revisions in addition to the mainline ones.'),
3921.3.6 by Marius Kruger
* fix some indentation anomalies in cmd_missing
4298
        ]
1816.1.2 by Alexander Belchenko
fix non-ascii messages handling in 'missing' command
4299
    encoding_type = 'replace'
1185.54.1 by Aaron Bentley
Import Kinnison's plugin
4300
1816.1.2 by Alexander Belchenko
fix non-ascii messages handling in 'missing' command
4301
    @display_command
1185.54.1 by Aaron Bentley
Import Kinnison's plugin
4302
    def run(self, other_branch=None, reverse=False, mine_only=False,
3677.1.1 by Vincent Ladeuil
Begin fixing bug #233817.
4303
            theirs_only=False,
4304
            log_format=None, long=False, short=False, line=False,
4305
            show_ids=False, verbose=False, this=False, other=False,
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
4306
            include_merges=False, revision=None, my_revision=None,
4307
            directory=u'.'):
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.
4308
        from bzrlib.missing import find_unmerged, iter_log_revisions
3778.5.1 by Martin Pool
missing -q is quieter (#284748)
4309
        def message(s):
4310
            if not is_quiet():
4311
                self.outf.write(s)
2528.1.1 by Martin Pool
Better option names for missing (elliot)
4312
4313
        if this:
3427.3.3 by John Arbash Meinel
Revert cmd_missing to use the original function, only now supply restrict
4314
            mine_only = this
2528.1.1 by Martin Pool
Better option names for missing (elliot)
4315
        if other:
3427.3.3 by John Arbash Meinel
Revert cmd_missing to use the original function, only now supply restrict
4316
            theirs_only = other
4317
        # TODO: We should probably check that we don't have mine-only and
4318
        #       theirs-only set, but it gets complicated because we also have
4319
        #       this and other which could be used.
4320
        restrict = 'all'
4321
        if mine_only:
4322
            restrict = 'local'
4323
        elif theirs_only:
4324
            restrict = 'remote'
2528.1.1 by Martin Pool
Better option names for missing (elliot)
4325
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
4326
        local_branch = Branch.open_containing(directory)[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4327
        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.
4328
1185.54.16 by Aaron Bentley
fixed location handling to match old missing
4329
        parent = local_branch.get_parent()
1185.54.1 by Aaron Bentley
Import Kinnison's plugin
4330
        if other_branch is None:
1185.54.16 by Aaron Bentley
fixed location handling to match old missing
4331
            other_branch = parent
4332
            if other_branch is None:
2485.8.11 by Vincent Ladeuil
Fix some display leaks in tests.
4333
                raise errors.BzrCommandError("No peer location known"
2485.8.17 by Vincent Ladeuil
Fix the fix.
4334
                                             " or specified.")
2193.4.1 by Alexander Belchenko
'bzr missing' without specifying location show remembered location unescaped
4335
            display_url = urlutils.unescape_for_display(parent,
4336
                                                        self.outf.encoding)
3778.5.1 by Martin Pool
missing -q is quieter (#284748)
4337
            message("Using saved parent location: "
3596.3.1 by James Westby
Give the user a bit more information about which saved location is being used.
4338
                    + display_url + "\n")
2193.4.1 by Alexander Belchenko
'bzr missing' without specifying location show remembered location unescaped
4339
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
4340
        remote_branch = Branch.open(other_branch)
1551.2.46 by abentley
Made bzr missing . work on win32
4341
        if remote_branch.base == local_branch.base:
4342
            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.
4343
        else:
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4344
            self.add_cleanup(remote_branch.lock_read().unlock)
3921.3.4 by Marius Kruger
add support to filter on local and remote revisions
4345
4346
        local_revid_range = _revision_range_to_revid_range(
3921.3.11 by Marius Kruger
swap options as per review:
4347
            _get_revision_range(my_revision, local_branch,
3921.3.9 by Marius Kruger
* add some blackbox tests and another whitebox test
4348
                self.name()))
3921.3.4 by Marius Kruger
add support to filter on local and remote revisions
4349
4350
        remote_revid_range = _revision_range_to_revid_range(
3921.3.11 by Marius Kruger
swap options as per review:
4351
            _get_revision_range(revision,
3921.3.9 by Marius Kruger
* add some blackbox tests and another whitebox test
4352
                remote_branch, self.name()))
3921.3.4 by Marius Kruger
add support to filter on local and remote revisions
4353
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.
4354
        local_extra, remote_extra = find_unmerged(
4355
            local_branch, remote_branch, restrict,
4356
            backward=not reverse,
4357
            include_merges=include_merges,
4358
            local_revid_range=local_revid_range,
4359
            remote_revid_range=remote_revid_range)
4360
4361
        if log_format is None:
4362
            registry = log.log_formatter_registry
4363
            log_format = registry.get_default(local_branch)
4364
        lf = log_format(to_file=self.outf,
4365
                        show_ids=show_ids,
4366
                        show_timezone='original')
4367
4368
        status_code = 0
4369
        if local_extra and not theirs_only:
4370
            message("You have %d extra revision(s):\n" %
4371
                len(local_extra))
4372
            for revision in iter_log_revisions(local_extra,
4373
                                local_branch.repository,
4374
                                verbose):
4375
                lf.log_revision(revision)
4376
            printed_local = True
4377
            status_code = 1
4378
        else:
4379
            printed_local = False
4380
4381
        if remote_extra and not mine_only:
4382
            if printed_local is True:
4383
                message("\n\n\n")
4384
            message("You are missing %d revision(s):\n" %
4385
                len(remote_extra))
4386
            for revision in iter_log_revisions(remote_extra,
4387
                                remote_branch.repository,
4388
                                verbose):
4389
                lf.log_revision(revision)
4390
            status_code = 1
4391
4392
        if mine_only and not local_extra:
4393
            # We checked local, and found nothing extra
4394
            message('This branch is up to date.\n')
4395
        elif theirs_only and not remote_extra:
4396
            # We checked remote, and found nothing extra
4397
            message('Other branch is up to date.\n')
4398
        elif not (mine_only or theirs_only or local_extra or
4399
                  remote_extra):
4400
            # We checked both branches, and neither one had extra
4401
            # revisions
4402
            message("Branches are up to date.\n")
4403
        self.cleanup_now()
1666.1.5 by Robert Collins
Merge bound branch test performance improvements.
4404
        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
4405
            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.
4406
            # handle race conditions - a parent might be set while we run.
4407
            if local_branch.get_parent() is None:
4408
                local_branch.set_parent(remote_branch.base)
1666.1.5 by Robert Collins
Merge bound branch test performance improvements.
4409
        return status_code
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4410
4411
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
4412
class cmd_pack(Command):
5131.2.3 by Martin
Merge bzr.dev to resolve conflicts
4413
    __doc__ = """Compress the data within a repository.
5108.1.1 by Parth Malwankar
initial support for 'pack --clean-obsolete-packs'. tested only manually.
4414
5108.1.6 by Parth Malwankar
fixed typo.
4415
    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.
4416
    bazaar supports automatic packing of repository, this operation is
4417
    normally not required to be done manually.
4418
5108.1.5 by Parth Malwankar
updated docstring for pack command with better warning.
4419
    During the pack operation, bazaar takes a backup of existing repository
4420
    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.
4421
    automatically when it is safe to do so. To save disk space by removing
4422
    the backed up pack files, the --clean-obsolete-packs option may be
4423
    used.
4424
5108.1.5 by Parth Malwankar
updated docstring for pack command with better warning.
4425
    Warning: If you use --clean-obsolete-packs and your machine crashes
4426
    during or immediately after repacking, you may be left with a state
4427
    where the deletion has been written to disk but the new packs have not
4428
    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.
4429
    """
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
4430
4431
    _see_also = ['repositories']
4432
    takes_args = ['branch_or_repo?']
5108.1.1 by Parth Malwankar
initial support for 'pack --clean-obsolete-packs'. tested only manually.
4433
    takes_options = [
4434
        Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
4435
        ]
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
4436
5108.1.1 by Parth Malwankar
initial support for 'pack --clean-obsolete-packs'. tested only manually.
4437
    def run(self, branch_or_repo='.', clean_obsolete_packs=False):
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
4438
        dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
4439
        try:
4440
            branch = dir.open_branch()
4441
            repository = branch.repository
4442
        except errors.NotBranchError:
4443
            repository = dir.open_repository()
5108.1.1 by Parth Malwankar
initial support for 'pack --clean-obsolete-packs'. tested only manually.
4444
        repository.pack(clean_obsolete_packs=clean_obsolete_packs)
2604.2.1 by Robert Collins
(robertc) Introduce a pack command.
4445
4446
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4447
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
4448
    __doc__ = """List the installed plugins.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4449
3193.2.3 by Alexander Belchenko
another formatting variant suggested by John Meinel.
4450
    This command displays the list of installed plugins including
4451
    version of plugin and a short description of each.
4452
4453
    --verbose shows the path where each plugin is located.
2617.3.1 by Ian Clatworthy
Make the plugins command public with better help
4454
4455
    A plugin is an external component for Bazaar that extends the
4456
    revision control system, by adding or replacing code in Bazaar.
4457
    Plugins can do a variety of things, including overriding commands,
4458
    adding new commands, providing additional network transports and
4459
    customizing log output.
4460
4988.4.2 by Martin Pool
Change url to canonical.com or wiki, plus some doc improvements in passing
4461
    See the Bazaar Plugin Guide <http://doc.bazaar.canonical.com/plugins/en/>
4462
    for further information on plugins including where to find them and how to
4463
    install them. Instructions are also provided there on how to write new
4464
    plugins using the Python programming language.
2617.3.1 by Ian Clatworthy
Make the plugins command public with better help
4465
    """
3193.2.3 by Alexander Belchenko
another formatting variant suggested by John Meinel.
4466
    takes_options = ['verbose']
2629.1.1 by Ian Clatworthy
(Ian Clatworthy) Tweak the 'make plugins public' change following feedback from lifeless
4467
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
4468
    @display_command
3193.2.3 by Alexander Belchenko
another formatting variant suggested by John Meinel.
4469
    def run(self, verbose=False):
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4470
        import bzrlib.plugin
4471
        from inspect import getdoc
3193.2.2 by Alexander Belchenko
new formatting of `bzr plugins` output.
4472
        result = []
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
4473
        for name, plugin in bzrlib.plugin.plugins().items():
3193.2.2 by Alexander Belchenko
new formatting of `bzr plugins` output.
4474
            version = plugin.__version__
4475
            if version == 'unknown':
4476
                version = ''
4477
            name_ver = '%s %s' % (name, version)
2762.2.1 by Robert Collins
* ``bzr plugins`` now lists the version number for each plugin in square
4478
            d = getdoc(plugin.module)
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4479
            if d:
3193.2.2 by Alexander Belchenko
new formatting of `bzr plugins` output.
4480
                doc = d.split('\n')[0]
4481
            else:
4482
                doc = '(no description)'
4483
            result.append((name_ver, doc, plugin.path()))
3193.2.3 by Alexander Belchenko
another formatting variant suggested by John Meinel.
4484
        for name_ver, doc, path in sorted(result):
4988.8.3 by Ed Bayiates Home
More builtin command UIFactory updates
4485
            self.outf.write("%s\n" % name_ver)
4486
            self.outf.write("   %s\n" % doc)
3193.2.3 by Alexander Belchenko
another formatting variant suggested by John Meinel.
4487
            if verbose:
4988.8.3 by Ed Bayiates Home
More builtin command UIFactory updates
4488
                self.outf.write("   %s\n" % path)
4489
            self.outf.write("\n")
1147 by Martin Pool
- split builtin commands into separate module bzrlib.builtins;
4490
4491
1185.16.24 by Martin Pool
- add and test 'testament' builtin command
4492
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
4493
    __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
4494
    takes_options = [
4495
            'revision',
4496
            Option('long', help='Produce long-format testament.'),
4497
            Option('strict',
4498
                   help='Produce a strict-format testament.')]
1185.16.24 by Martin Pool
- add and test 'testament' builtin command
4499
    takes_args = ['branch?']
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
4500
    @display_command
1551.7.1 by Aaron Bentley
Implement --strict at commandline, fix up strict format
4501
    def run(self, branch=u'.', revision=None, long=False, strict=False):
4502
        from bzrlib.testament import Testament, StrictTestament
4503
        if strict is True:
4504
            testament_class = StrictTestament
4505
        else:
4506
            testament_class = Testament
3530.2.1 by John Arbash Meinel
'bzr testament' should just open the branch
4507
        if branch == '.':
4508
            b = Branch.open_containing(branch)[0]
4509
        else:
4510
            b = Branch.open(branch)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4511
        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.
4512
        if revision is None:
4513
            rev_id = b.last_revision()
4514
        else:
4515
            rev_id = revision[0].as_revision_id(b)
4516
        t = testament_class.from_revision(b.repository, rev_id)
4517
        if long:
4518
            sys.stdout.writelines(t.as_text_lines())
4519
        else:
4520
            sys.stdout.write(t.as_short_text())
1185.16.32 by Martin Pool
- add a basic annotate built-in command
4521
4522
4523
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
4524
    __doc__ = """Show the origin of each line in a file.
1185.16.32 by Martin Pool
- add a basic annotate built-in command
4525
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
4526
    This prints out the given file with an annotation on the left side
4527
    indicating which revision, author and date introduced the change.
4528
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4529
    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
4530
    shown only at the top, unless the --all option is given.
1185.16.32 by Martin Pool
- add a basic annotate built-in command
4531
    """
4532
    # TODO: annotate directories; showing when each file was last changed
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4533
    # 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
4534
    #       with new uncommitted lines marked
1733.2.8 by Michael Ellerman
Add CVS compatible aliases for checkout and annotate, from fullermd.
4535
    aliases = ['ann', 'blame', 'praise']
1185.16.32 by Martin Pool
- add a basic annotate built-in command
4536
    takes_args = ['filename']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
4537
    takes_options = [Option('all', help='Show annotations on all lines.'),
4538
                     Option('long', help='Show commit date in annotations.'),
2182.3.1 by John Arbash Meinel
Annotate now shows dotted revnos instead of plain revnos.
4539
                     'revision',
4540
                     'show-ids',
5171.3.3 by Martin von Gagern
Add --directory option to ls, cat and annotate.
4541
                     'directory',
1185.16.53 by Martin Pool
- annotate improvements from Goffreddo, with extra bug fixes and tests
4542
                     ]
2593.1.1 by Adeodato Simó
Improve annotate to prevent unicode exceptions in certain situations.
4543
    encoding_type = 'exact'
1185.16.32 by Martin Pool
- add a basic annotate built-in command
4544
1185.12.56 by Aaron Bentley
Prevented display commands from printing broken pipe errors
4545
    @display_command
2182.3.1 by John Arbash Meinel
Annotate now shows dotted revnos instead of plain revnos.
4546
    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.
4547
            show_ids=False, directory=None):
3603.4.1 by Robert Collins
Implement lookups into the current working tree for bzr annotate, fixing bug 3439.
4548
        from bzrlib.annotate import annotate_file, annotate_file_tree
3146.2.1 by Lukáš Lalinský
Don't require a working tree in cmd_annotate.
4549
        wt, branch, relpath = \
5171.3.9 by Martin von Gagern
Rename function to _open_directory_or_containing_tree_or_branch.
4550
            _open_directory_or_containing_tree_or_branch(filename, directory)
3146.2.1 by Lukáš Lalinský
Don't require a working tree in cmd_annotate.
4551
        if wt is not None:
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4552
            self.add_cleanup(wt.lock_read().unlock)
3146.2.1 by Lukáš Lalinský
Don't require a working tree in cmd_annotate.
4553
        else:
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4554
            self.add_cleanup(branch.lock_read().unlock)
4900.1.2 by Andrew Bennetts
Use Command.add_cleanup to fix ObjectNotLocked bug in cmd_annotate.
4555
        tree = _get_one_revision_tree('annotate', revision, branch=branch)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4556
        self.add_cleanup(tree.lock_read().unlock)
4900.1.2 by Andrew Bennetts
Use Command.add_cleanup to fix ObjectNotLocked bug in cmd_annotate.
4557
        if wt is not None:
4558
            file_id = wt.path2id(relpath)
4559
        else:
4560
            file_id = tree.path2id(relpath)
4561
        if file_id is None:
4562
            raise errors.NotVersionedError(filename)
4563
        file_version = tree.inventory[file_id].revision
4564
        if wt is not None and revision is None:
4565
            # If there is a tree and we're not annotating historical
4566
            # versions, annotate the working tree's content.
4567
            annotate_file_tree(wt, file_id, self.outf, long, all,
4568
                show_ids=show_ids)
4569
        else:
4570
            annotate_file(branch, file_version, file_id, long, all, self.outf,
4571
                          show_ids=show_ids)
1185.16.33 by Martin Pool
- move 'conflict' and 'resolved' from shipped plugin to regular builtins
4572
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
4573
4574
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
4575
    __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.
4576
    # TODO be able to replace existing ones.
4577
4578
    hidden = True # is this right ?
1185.78.1 by John Arbash Meinel
Updating bzr re-sign to allow multiple arguments, and updating tests
4579
    takes_args = ['revision_id*']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
4580
    takes_options = ['directory', 'revision']
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4581
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
4582
    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
4583
        if revision_id_list is not None and revision is not None:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
4584
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
1185.78.1 by John Arbash Meinel
Updating bzr re-sign to allow multiple arguments, and updating tests
4585
        if revision_id_list is None and revision is None:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
4586
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
4587
        b = WorkingTree.open_containing(directory)[0].branch
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4588
        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.
4589
        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.
4590
4591
    def _run(self, b, revision_id_list, revision):
4592
        import bzrlib.gpg as gpg
1770.2.9 by Aaron Bentley
Add Branch.get_config, update BranchConfig() callers
4593
        gpg_strategy = gpg.GPGStrategy(b.get_config())
1185.78.1 by John Arbash Meinel
Updating bzr re-sign to allow multiple arguments, and updating tests
4594
        if revision_id_list is not None:
3010.1.17 by Robert Collins
Lock correctness and commit_group management for re-sign, in builtins.
4595
            b.repository.start_write_group()
4596
            try:
4597
                for revision_id in revision_id_list:
4598
                    b.repository.sign_revision(revision_id, gpg_strategy)
4599
            except:
4600
                b.repository.abort_write_group()
4601
                raise
4602
            else:
4603
                b.repository.commit_write_group()
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
4604
        elif revision is not None:
1483 by Robert Collins
BUGFIX: re-sign should accept ranges
4605
            if len(revision) == 1:
4606
                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.
4607
                b.repository.start_write_group()
4608
                try:
4609
                    b.repository.sign_revision(rev_id, gpg_strategy)
4610
                except:
4611
                    b.repository.abort_write_group()
4612
                    raise
4613
                else:
4614
                    b.repository.commit_write_group()
1483 by Robert Collins
BUGFIX: re-sign should accept ranges
4615
            elif len(revision) == 2:
4616
                # are they both on rh- if so we can walk between them
4617
                # might be nice to have a range helper for arbitrary
4618
                # revision paths. hmm.
4619
                from_revno, from_revid = revision[0].in_history(b)
4620
                to_revno, to_revid = revision[1].in_history(b)
4621
                if to_revid is None:
4622
                    to_revno = b.revno()
4623
                if from_revno is None or to_revno is None:
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
4624
                    raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
3010.1.17 by Robert Collins
Lock correctness and commit_group management for re-sign, in builtins.
4625
                b.repository.start_write_group()
4626
                try:
4627
                    for revno in range(from_revno, to_revno + 1):
4628
                        b.repository.sign_revision(b.get_rev_id(revno),
4629
                                                   gpg_strategy)
4630
                except:
4631
                    b.repository.abort_write_group()
4632
                    raise
4633
                else:
4634
                    b.repository.commit_write_group()
1483 by Robert Collins
BUGFIX: re-sign should accept ranges
4635
            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
4636
                raise errors.BzrCommandError('Please supply either one revision, or a range.')
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
4637
1505.1.22 by John Arbash Meinel
Some small cleanup and discussion in preparation for modifying commit, pull, and merge
4638
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
4639
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
4640
    __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
4641
    If no branch is supplied, rebind to the last bound location.
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
4642
2270.1.2 by John Arbash Meinel
Tweak the help text for bind/unbind according to Robert's suggestions.
4643
    Once converted into a checkout, commits must succeed on the master branch
4644
    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.
4645
3565.6.16 by Marius Kruger
update nick command description to mention how it works for bound branches,
4646
    Bound branches use the nickname of its master branch unless it is set
4775.1.1 by Martin Pool
Remove several 'the the' typos
4647
    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.
4648
    that of the master.
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
4649
    """
4650
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
4651
    _see_also = ['checkouts', 'unbind']
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
4652
    takes_args = ['location?']
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
4653
    takes_options = ['directory']
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
4654
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
4655
    def run(self, location=None, directory=u'.'):
4656
        b, relpath = Branch.open_containing(directory)
2230.3.31 by Aaron Bentley
Implement re-binding previously-bound branches
4657
        if location is None:
4658
            try:
4659
                location = b.get_old_bound_location()
4660
            except errors.UpgradeRequired:
4661
                raise errors.BzrCommandError('No location supplied.  '
4662
                    'This format does not remember old locations.')
4663
            else:
4664
                if location is None:
4988.7.1 by Neil Martinsen-Burrell
better error message for bzr bind on and already bound branch
4665
                    if b.get_bound_location() is not None:
4666
                        raise errors.BzrCommandError('Branch is already bound')
4667
                    else:
4668
                        raise errors.BzrCommandError('No location supplied '
4669
                            'and no previous location known')
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
4670
        b_other = Branch.open(location)
1505.1.3 by John Arbash Meinel
(broken) Adding more tests, and some functionality
4671
        try:
4672
            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
4673
        except errors.DivergedBranches:
4674
            raise errors.BzrCommandError('These branches have diverged.'
4675
                                         ' Try merging, and then bind again.')
3565.6.11 by Marius Kruger
Bind now updates explicit nicks
4676
        if b.get_config().has_explicit_nickname():
4677
            b.nick = b_other.nick
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
4678
1505.1.22 by John Arbash Meinel
Some small cleanup and discussion in preparation for modifying commit, pull, and merge
4679
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
4680
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
4681
    __doc__ = """Convert the current checkout into a regular branch.
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
4682
2270.1.2 by John Arbash Meinel
Tweak the help text for bind/unbind according to Robert's suggestions.
4683
    After unbinding, the local branch is considered independent and subsequent
4684
    commits will be local only.
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
4685
    """
4686
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
4687
    _see_also = ['checkouts', 'bind']
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
4688
    takes_args = []
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
4689
    takes_options = ['directory']
1505.1.2 by John Arbash Meinel
(broken) working on implementing bound branches.
4690
5171.3.2 by Martin von Gagern
Add --directory option to 13 more commands.
4691
    def run(self, directory=u'.'):
4692
        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
4693
        if not b.unbind():
1996.3.34 by John Arbash Meinel
Update builtins to use errors.foo. Now errors can be avoided entirely for a bzr rocks run
4694
            raise errors.BzrCommandError('Local branch is not bound')
1505.1.22 by John Arbash Meinel
Some small cleanup and discussion in preparation for modifying commit, pull, and merge
4695
1442.1.59 by Robert Collins
Add re-sign command to generate a digital signature on a single revision.
4696
1773.4.1 by Martin Pool
Add pyflakes makefile target; fix many warnings
4697
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
4698
    __doc__ = """Remove the last committed revision.
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
4699
4700
    --verbose will print out what is being removed.
4701
    --dry-run will go through all the motions, but not actually
4702
    remove anything.
2747.2.1 by Daniel Watkins
Modified the help message of 'uncommit'.
4703
4704
    If --revision is specified, uncommit revisions to leave the branch at the
4705
    specified revision.  For example, "bzr uncommit -r 15" will leave the
4706
    branch at revision 15.
4707
1551.19.39 by Aaron Bentley
Update 'uncommit' docs
4708
    Uncommit leaves the working tree ready for a new commit.  The only change
4709
    it may make is to restore any pending merges that were present before
4710
    the commit.
1553.5.34 by Martin Pool
Stub lock-breaking command
4711
    """
1185.62.11 by John Arbash Meinel
Added TODO for bzr uncommit to remove unreferenced information.
4712
1553.5.34 by Martin Pool
Stub lock-breaking command
4713
    # TODO: jam 20060108 Add an option to allow uncommit to remove
1759.2.1 by Jelmer Vernooij
Fix some types (found using aspell).
4714
    # unreferenced information in 'branch-as-repository' branches.
1553.5.34 by Martin Pool
Stub lock-breaking command
4715
    # TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
4716
    # information in shared branches as well.
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
4717
    _see_also = ['commit']
1185.62.10 by John Arbash Meinel
Removed --all from bzr uncommit, it was broken anyway.
4718
    takes_options = ['verbose', 'revision',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
4719
                    Option('dry-run', help='Don\'t actually make changes.'),
3280.4.1 by John Arbash Meinel
Add uncommit --local.
4720
                    Option('force', help='Say yes to all questions.'),
4721
                    Option('local',
4722
                           help="Only remove the commits from the local branch"
4723
                                " when in a checkout."
4724
                           ),
4725
                    ]
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
4726
    takes_args = ['location?']
4727
    aliases = []
3101.1.1 by Aaron Bentley
Uncommit doesn't throw when it encounters un-encodable characters
4728
    encoding_type = 'replace'
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
4729
1850.3.2 by John Arbash Meinel
Change uncommit -r 10 so that it uncommits *to* 10, rather than removing 10
4730
    def run(self, location=None,
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
4731
            dry_run=False, verbose=False,
3280.4.1 by John Arbash Meinel
Add uncommit --local.
4732
            revision=None, force=False, local=False):
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
4733
        if location is None:
1185.33.66 by Martin Pool
[patch] use unicode literals for all hardcoded paths (Alexander Belchenko)
4734
            location = u'.'
1558.1.12 by Aaron Bentley
Got uncommit working properly with checkouts
4735
        control, relpath = bzrdir.BzrDir.open_containing(location)
4736
        try:
4737
            tree = control.open_workingtree()
1558.9.1 by Aaron Bentley
Fix uncommit to handle bound branches, and to do locking
4738
            b = tree.branch
1558.1.12 by Aaron Bentley
Got uncommit working properly with checkouts
4739
        except (errors.NoWorkingTree, errors.NotLocalUrl):
4740
            tree = None
1558.9.1 by Aaron Bentley
Fix uncommit to handle bound branches, and to do locking
4741
            b = control.open_branch()
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
4742
3065.2.2 by John Arbash Meinel
During bzr uncommit, lock the working tree if it is available.
4743
        if tree is not None:
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4744
            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.
4745
        else:
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
4746
            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.
4747
        return self._run(b, tree, dry_run, verbose, revision, force, local=local)
3065.2.1 by Lukáš Lalinský
Add a global branch write lock to cmd_uncommit and avoid unnecessary Branch.revno calls.
4748
3280.4.1 by John Arbash Meinel
Add uncommit --local.
4749
    def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
3065.2.1 by Lukáš Lalinský
Add a global branch write lock to cmd_uncommit and avoid unnecessary Branch.revno calls.
4750
        from bzrlib.log import log_formatter, show_log
4751
        from bzrlib.uncommit import uncommit
4752
4753
        last_revno, last_rev_id = b.last_revision_info()
4754
1850.3.2 by John Arbash Meinel
Change uncommit -r 10 so that it uncommits *to* 10, rather than removing 10
4755
        rev_id = None
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
4756
        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.
4757
            revno = last_revno
4758
            rev_id = last_rev_id
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
4759
        else:
1850.3.2 by John Arbash Meinel
Change uncommit -r 10 so that it uncommits *to* 10, rather than removing 10
4760
            # 'bzr uncommit -r 10' actually means uncommit
4761
            # so that the final tree is at revno 10.
4762
            # but bzrlib.uncommit.uncommit() actually uncommits
4763
            # the revisions that are supplied.
4764
            # 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.
4765
            revno = revision[0].in_history(b).revno + 1
4766
            if revno <= last_revno:
4767
                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
4768
2948.2.2 by John Arbash Meinel
Re-introduce the None check in case someone asks to uncommit *to* the last revision
4769
        if rev_id is None or _mod_revision.is_null(rev_id):
4988.8.3 by Ed Bayiates Home
More builtin command UIFactory updates
4770
            self.outf.write('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
4771
            return 1
4772
4773
        lf = log_formatter('short',
4988.8.3 by Ed Bayiates Home
More builtin command UIFactory updates
4774
                           to_file=self.outf,
3629.1.2 by John Arbash Meinel
Change to just display the command to restore the tip,
4775
                           show_timezone='original')
1850.3.2 by John Arbash Meinel
Change uncommit -r 10 so that it uncommits *to* 10, rather than removing 10
4776
4777
        show_log(b,
4778
                 lf,
4779
                 verbose=False,
4780
                 direction='forward',
4781
                 start_revision=revno,
3065.2.1 by Lukáš Lalinský
Add a global branch write lock to cmd_uncommit and avoid unnecessary Branch.revno calls.
4782
                 end_revision=last_revno)
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
4783
4784
        if dry_run:
4988.8.4 by Vincent Ladeuil
Fix lines too long, fix inverted assertions.
4785
            self.outf.write('Dry-run, pretending to remove'
4786
                            ' the above revisions.\n')
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
4787
        else:
4988.8.3 by Ed Bayiates Home
More builtin command UIFactory updates
4788
            self.outf.write('The above revision(s) will be removed.\n')
4988.8.1 by Ed Bayiates
Updated builtins.py cmd_uncommit to use UIFactory
4789
4790
        if not force:
4988.8.3 by Ed Bayiates Home
More builtin command UIFactory updates
4791
            if not ui.ui_factory.get_boolean('Are you sure'):
4792
                self.outf.write('Canceled')
4988.8.1 by Ed Bayiates
Updated builtins.py cmd_uncommit to use UIFactory
4793
                return 0
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
4794
3629.1.1 by John Arbash Meinel
Change 'bzr uncommit' to display the revision ids and log them.
4795
        mutter('Uncommitting from {%s} to {%s}',
4796
               last_rev_id, rev_id)
1558.1.12 by Aaron Bentley
Got uncommit working properly with checkouts
4797
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
3280.4.1 by John Arbash Meinel
Add uncommit --local.
4798
                 revno=revno, local=local)
4988.8.3 by Ed Bayiates Home
More builtin command UIFactory updates
4799
        self.outf.write('You can restore the old tip by running:\n'
4800
             '  bzr pull . -r revid:%s\n' % last_rev_id)
1185.31.24 by John Arbash Meinel
[merge] Added the uncommit plugin
4801
4802
1553.5.34 by Martin Pool
Stub lock-breaking command
4803
class cmd_break_lock(Command):
5131.2.1 by Martin
Permit bzrlib to run under python -OO by explictly assigning to __doc__ for user-visible docstrings
4804
    __doc__ = """Break a dead lock on a repository, branch or working directory.
1553.5.34 by Martin Pool
Stub lock-breaking command
4805
1553.5.35 by Martin Pool
Start break-lock --show
4806
    CAUTION: Locks should only be broken when you are sure that the process
1553.5.34 by Martin Pool
Stub lock-breaking command
4807
    holding the lock has been stopped.
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
4808
4960.2.3 by Martin Pool
Better break-lock help
4809
    You can get information on what locks are open via the 'bzr info
4810
    [location]' command.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4811
2666.1.1 by Ian Clatworthy
Bazaar User Reference generated from online help
4812
    :Examples:
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
4813
        bzr break-lock
4960.2.3 by Martin Pool
Better break-lock help
4814
        bzr break-lock bzr+ssh://example.com/bzr/foo
1553.5.34 by Martin Pool
Stub lock-breaking command
4815
    """
1687.1.12 by Robert Collins
Hook in the full break-lock ui.
4816
    takes_args = ['location?']
4817
4818
    def run(self, location=None, show=False):
4819
        if location is None:
4820
            location = u'.'
4821
        control, relpath = bzrdir.BzrDir.open_containing(location)
1687.1.17 by Robert Collins
Test break lock on old format branches.
4822
        try:
4823
            control.break_lock()
4824
        except NotImplementedError:
4825
            pass
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4826
1553.5.35 by Martin Pool
Start break-lock --show
4827
1910.17.2 by Andrew Bennetts
Add start_bzr_subprocess and stop_bzr_subprocess to allow test code to continue
4828
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
4829
    __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
4830
4831
    This just prints a line to signal when it is ready, then blocks on stdin.
4832
    """
4833
4834
    hidden = True
4835
4836
    def run(self):
1910.17.6 by Andrew Bennetts
Use sys.stdout consistently, rather than mixed with print.
4837
        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
4838
        sys.stdout.flush()
4839
        sys.stdin.readline()
4840
1553.5.35 by Martin Pool
Start break-lock --show
4841
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
4842
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
4843
    __doc__ = """Run the bzr server."""
2020.1.1 by Robert Collins
Add readonly support to the smart server, enabled by default via `bzr server`.
4844
4845
    aliases = ['server']
4846
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
4847
    takes_options = [
4848
        Option('inet',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
4849
               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.
4850
        RegistryOption('protocol',
4851
               help="Protocol to serve.",
4370.4.6 by Jelmer Vernooij
Move server protocol registry to bzrlib.transport.
4852
               lazy_registry=('bzrlib.transport', 'transport_server_registry'),
4370.4.1 by Jelmer Vernooij
Add registry for 'bzr serve' protocols.
4853
               value_switches=True),
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
4854
        Option('port',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
4855
               help='Listen for connections on nominated port of the form '
4856
                    '[hostname:]portnumber.  Passing 0 as the port number will '
4370.4.1 by Jelmer Vernooij
Add registry for 'bzr serve' protocols.
4857
                    'result in a dynamically allocated port.  The default port '
4858
                    'depends on the protocol.',
1910.19.7 by Andrew Bennetts
Allow specifying the host/interface to bzr serve, and use the new test
4859
               type=str),
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
4860
        custom_help('directory',
4861
               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`.
4862
        Option('allow-writes',
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
4863
               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`.
4864
                    '--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.
4865
                    'the served directory and below.  Note that ``bzr serve`` '
4866
                    'does not perform authentication, so unless some form of '
4867
                    'external authentication is arranged supplying this '
4868
                    'option leads to global uncontrolled write access to your '
4869
                    'file system.'
2020.1.1 by Robert Collins
Add readonly support to the smart server, enabled by default via `bzr server`.
4870
                ),
1910.19.1 by Andrew Bennetts
Support bzr:// urls to work with the new RPC-based transport which will be used
4871
        ]
4872
3955.1.4 by Jonathan Lange
Docstrings and extraction of method to get the smart server.
4873
    def get_host_and_port(self, port):
4874
        """Return the host and port to run the smart server on.
4875
4370.4.3 by Jelmer Vernooij
Move host/port parsing to early in bzr-serve.
4876
        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.
4877
4878
        If 'port' has a colon in it, the string before the colon will be
4879
        interpreted as the host.
4880
4881
        :param port: A string of the port to run the server on.
4882
        :return: A tuple of (host, port), where 'host' is a host name or IP,
4883
            and port is an integer TCP/IP port.
4884
        """
4370.4.3 by Jelmer Vernooij
Move host/port parsing to early in bzr-serve.
4885
        host = None
4370.4.7 by Jelmer Vernooij
Review feedback from Ian.
4886
        if port is not None:
3955.1.2 by Jonathan Lange
Extract the port-getting logic. Use note() rather than print()
4887
            if ':' in port:
4888
                host, port = port.split(':')
4889
            port = int(port)
4890
        return host, port
4891
4370.4.1 by Jelmer Vernooij
Add registry for 'bzr serve' protocols.
4892
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
4893
            protocol=None):
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
4894
        from bzrlib import transport
4370.4.1 by Jelmer Vernooij
Add registry for 'bzr serve' protocols.
4895
        if directory is None:
4896
            directory = os.getcwd()
4897
        if protocol is None:
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
4898
            protocol = transport.transport_server_registry.get()
4370.4.3 by Jelmer Vernooij
Move host/port parsing to early in bzr-serve.
4899
        host, port = self.get_host_and_port(port)
4370.4.4 by Jelmer Vernooij
Move more bzr smart server-specific stuff into a single function.
4900
        url = urlutils.local_path_to_url(directory)
4901
        if not allow_writes:
4902
            url = 'readonly+' + url
5273.1.7 by Vincent Ladeuil
No more use of the get_transport imported *symbol*, all uses are through
4903
        t = transport.get_transport(url)
4904
        protocol(t, host, port, inet)
4370.4.1 by Jelmer Vernooij
Add registry for 'bzr serve' protocols.
4905
3955.1.2 by Jonathan Lange
Extract the port-getting logic. Use note() rather than print()
4906
1731.2.7 by Aaron Bentley
Add join command
4907
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
4908
    __doc__ = """Combine a tree into its containing tree.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4909
4251.1.2 by Aaron Bentley
Hide the --reference option.
4910
    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
4911
4912
    The TREE argument should be an independent tree, inside another tree, but
4913
    not part of it.  (Such trees can be produced by "bzr split", but also by
4914
    running "bzr branch" with the target inside a tree.)
4915
4916
    The result is a combined tree, with the subtree no longer an independant
4917
    part.  This is marked as a merge of the subtree into the containing tree,
4918
    and all history is preserved.
1731.2.7 by Aaron Bentley
Add join command
4919
    """
4920
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
4921
    _see_also = ['split']
1731.2.7 by Aaron Bentley
Add join command
4922
    takes_args = ['tree']
2598.1.1 by Martin Pool
Add test for and documentation of option style, fix up existing options to comply
4923
    takes_options = [
4251.1.2 by Aaron Bentley
Hide the --reference option.
4924
            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
4925
            ]
1731.2.7 by Aaron Bentley
Add join command
4926
2100.3.11 by Aaron Bentley
Add join --reference support
4927
    def run(self, tree, reference=False):
1731.2.7 by Aaron Bentley
Add join command
4928
        sub_tree = WorkingTree.open(tree)
4929
        parent_dir = osutils.dirname(sub_tree.basedir)
4930
        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
4931
        repo = containing_tree.branch.repository
4932
        if not repo.supports_rich_root():
4933
            raise errors.BzrCommandError(
4934
                "Can't join trees because %s doesn't support rich root data.\n"
4935
                "You can use bzr upgrade on the repository."
4936
                % (repo,))
2100.3.11 by Aaron Bentley
Add join --reference support
4937
        if reference:
2255.2.219 by Martin Pool
fix unbound local error in cmd_join
4938
            try:
2100.3.11 by Aaron Bentley
Add join --reference support
4939
                containing_tree.add_reference(sub_tree)
2255.2.219 by Martin Pool
fix unbound local error in cmd_join
4940
            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
4941
                # XXX: Would be better to just raise a nicely printable
4942
                # exception from the real origin.  Also below.  mbp 20070306
2255.2.219 by Martin Pool
fix unbound local error in cmd_join
4943
                raise errors.BzrCommandError("Cannot join %s.  %s" %
2100.3.11 by Aaron Bentley
Add join --reference support
4944
                                             (tree, e.reason))
4945
        else:
4946
            try:
4947
                containing_tree.subsume(sub_tree)
4948
            except errors.BadSubsumeSource, e:
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
4949
                raise errors.BzrCommandError("Cannot join %s.  %s" %
2100.3.11 by Aaron Bentley
Add join --reference support
4950
                                             (tree, e.reason))
1553.5.35 by Martin Pool
Start break-lock --show
4951
1731.2.22 by Aaron Bentley
Initial work on split command
4952
4953
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
4954
    __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
4955
3113.6.2 by Aaron Bentley
Un-hide split command, add NEWS
4956
    This command will produce a target tree in a format that supports
4957
    rich roots, like 'rich-root' or 'rich-root-pack'.  These formats cannot be
4958
    converted into earlier formats like 'dirstate-tags'.
2338.3.1 by Aaron Bentley
Hide nested-tree commands and improve their docs
4959
4960
    The TREE argument should be a subdirectory of a working tree.  That
4961
    subdirectory will be converted into an independent tree, with its own
4962
    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
4963
    """
4964
4251.1.4 by Aaron Bentley
Uncomment split's 'See also:join'
4965
    _see_also = ['join']
1731.2.22 by Aaron Bentley
Initial work on split command
4966
    takes_args = ['tree']
4967
4968
    def run(self, tree):
4969
        containing_tree, subdir = WorkingTree.open_containing(tree)
4970
        sub_id = containing_tree.path2id(subdir)
4971
        if sub_id is None:
4972
            raise errors.NotVersionedError(subdir)
1731.2.23 by Aaron Bentley
Throw user-friendly error splitting in shared repo with wrong format
4973
        try:
4974
            containing_tree.extract(sub_id)
4975
        except errors.RootNotRich:
4416.6.1 by Neil Martinsen-Burrell
Fix #220067 adding more specificity to the error message when split fails
4976
            raise errors.RichRootUpgradeRequired(containing_tree.branch.base)
1731.2.22 by Aaron Bentley
Initial work on split command
4977
4978
1551.12.8 by Aaron Bentley
Add merge-directive command
4979
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
4980
    __doc__ = """Generate a merge directive for auto-merge tools.
1551.12.32 by Aaron Bentley
Improve merge directive help
4981
4982
    A directive requests a merge to be performed, and also provides all the
4983
    information necessary to do so.  This means it must either include a
4984
    revision bundle, or the location of a branch containing the desired
4985
    revision.
4986
4987
    A submit branch (the location to merge into) must be supplied the first
4988
    time the command is issued.  After it has been supplied once, it will
4989
    be remembered as the default.
4990
4991
    A public branch is optional if a revision bundle is supplied, but required
4992
    if --diff or --plain is specified.  It will be remembered as the default
4993
    after the first use.
4994
    """
1551.12.20 by Aaron Bentley
Pull directive registry into command class
4995
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
4996
    takes_args = ['submit_branch?', 'public_branch?']
4997
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
4998
    hidden = True
4999
2681.1.4 by Aaron Bentley
Fix reference to told submit command
5000
    _see_also = ['send']
2520.4.121 by Aaron Bentley
Polish up submit command
5001
1551.12.43 by Aaron Bentley
Misc changes from review
5002
    takes_options = [
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
5003
        'directory',
1551.12.43 by Aaron Bentley
Misc changes from review
5004
        RegistryOption.from_kwargs('patch-type',
2681.1.7 by Aaron Bentley
Fix option grammar
5005
            '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
5006
            title='Patch type',
5007
            value_switches=True,
5008
            enum_switch=False,
5009
            bundle='Bazaar revision bundle (default).',
5010
            diff='Normal unified diff.',
5011
            plain='No patch, just directive.'),
5012
        Option('sign', help='GPG-sign the directive.'), 'revision',
1551.12.26 by Aaron Bentley
Get email working, with optional message
5013
        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
5014
            help='Instead of printing the directive, email to this address.'),
1551.12.27 by Aaron Bentley
support custom message everywhere
5015
        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
5016
            help='Message to use when committing this merge.')
1551.12.27 by Aaron Bentley
support custom message everywhere
5017
        ]
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
5018
2530.2.1 by Adeodato Simó
Add encoding_type = 'exact' to cmd_merge_directive. (LP #120591)
5019
    encoding_type = 'exact'
5020
1551.12.16 by Aaron Bentley
Enable signing merge directives
5021
    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.
5022
            sign=False, revision=None, mail_to=None, message=None,
5023
            directory=u'.'):
2490.2.28 by Aaron Bentley
Fix handling of null revision
5024
        from bzrlib.revision import ensure_null, NULL_REVISION
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
5025
        include_patch, include_bundle = {
5026
            'plain': (False, False),
5027
            'diff': (True, False),
5028
            'bundle': (True, True),
5029
            }[patch_type]
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
5030
        branch = Branch.open(directory)
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
5031
        stored_submit_branch = branch.get_submit_branch()
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
5032
        if submit_branch is None:
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
5033
            submit_branch = stored_submit_branch
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
5034
        else:
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
5035
            if stored_submit_branch is None:
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
5036
                branch.set_submit_branch(submit_branch)
5037
        if submit_branch is None:
5038
            submit_branch = branch.get_parent()
5039
        if submit_branch is None:
5040
            raise errors.BzrCommandError('No submit branch specified or known')
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
5041
5042
        stored_public_branch = branch.get_public_branch()
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
5043
        if public_branch is None:
1551.12.44 by Aaron Bentley
Add (set|get)_public_branch
5044
            public_branch = stored_public_branch
5045
        elif stored_public_branch is None:
5046
            branch.set_public_branch(public_branch)
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
5047
        if not include_bundle and public_branch is None:
1551.12.24 by Aaron Bentley
Add RegistryOption.from_swargs to simplify simple registry options
5048
            raise errors.BzrCommandError('No public branch specified or'
5049
                                         ' known')
2520.4.112 by Aaron Bentley
Make cherry-pick merge directives possible
5050
        base_revision_id = None
1551.12.17 by Aaron Bentley
add revision selection to mergedirective
5051
        if revision is not None:
2520.4.112 by Aaron Bentley
Make cherry-pick merge directives possible
5052
            if len(revision) > 2:
1551.12.17 by Aaron Bentley
add revision selection to mergedirective
5053
                raise errors.BzrCommandError('bzr merge-directive takes '
2520.4.112 by Aaron Bentley
Make cherry-pick merge directives possible
5054
                    '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()
5055
            revision_id = revision[-1].as_revision_id(branch)
2520.4.112 by Aaron Bentley
Make cherry-pick merge directives possible
5056
            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()
5057
                base_revision_id = revision[0].as_revision_id(branch)
1551.12.17 by Aaron Bentley
add revision selection to mergedirective
5058
        else:
5059
            revision_id = branch.last_revision()
2490.2.28 by Aaron Bentley
Fix handling of null revision
5060
        revision_id = ensure_null(revision_id)
5061
        if revision_id == NULL_REVISION:
5062
            raise errors.BzrCommandError('No revisions to bundle.')
2520.4.73 by Aaron Bentley
Implement new merge directive format
5063
        directive = merge_directive.MergeDirective2.from_objects(
1551.12.17 by Aaron Bentley
add revision selection to mergedirective
5064
            branch.repository, revision_id, time.time(),
1551.12.8 by Aaron Bentley
Add merge-directive command
5065
            osutils.local_time_offset(), submit_branch,
2520.5.4 by Aaron Bentley
Replace 'bundle-revisions' with 'submit' command
5066
            public_branch=public_branch, include_patch=include_patch,
5067
            include_bundle=include_bundle, message=message,
5068
            base_revision_id=base_revision_id)
1551.12.26 by Aaron Bentley
Get email working, with optional message
5069
        if mail_to is None:
5070
            if sign:
5071
                self.outf.write(directive.to_signed(branch))
5072
            else:
5073
                self.outf.writelines(directive.to_lines())
1551.12.16 by Aaron Bentley
Enable signing merge directives
5074
        else:
1551.12.26 by Aaron Bentley
Get email working, with optional message
5075
            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.
5076
            s = SMTPConnection(branch.get_config())
5077
            s.send_email(message)
1551.12.8 by Aaron Bentley
Add merge-directive command
5078
1551.12.14 by Aaron Bentley
Get merge-directive command basically working
5079
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5080
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
5081
    __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.
5082
5083
    A merge directive provides many things needed for requesting merges:
5084
5085
    * A machine-readable description of the merge to perform
5086
5087
    * An optional patch that is a preview of the changes requested
5088
5089
    * An optional bundle of revision data, so that the changes can be applied
5090
      directly from the merge directive, without retrieving data from a
5091
      branch.
5092
4949.2.1 by Martin Pool
Better help for cmd_send
5093
    `bzr send` creates a compact data set that, when applied using bzr
5094
    merge, has the same effect as merging from the source branch.  
5095
    
5096
    By default the merge directive is self-contained and can be applied to any
5097
    branch containing submit_branch in its ancestory without needing access to
5098
    the source branch.
5099
    
5100
    If --no-bundle is specified, then Bazaar doesn't send the contents of the
5101
    revisions, but only a structured request to merge from the
5102
    public_location.  In that case the public_branch is needed and it must be
5103
    up-to-date and accessible to the recipient.  The public_branch is always
5104
    included if known, so that people can check it later.
5105
5106
    The submit branch defaults to the parent of the source branch, but can be
5107
    overridden.  Both submit branch and public branch will be remembered in
5108
    branch.conf the first time they are used for a particular branch.  The
5109
    source branch defaults to that containing the working directory, but can
5110
    be changed using --from.
5111
5112
    In order to calculate those changes, bzr must analyse the submit branch.
5113
    Therefore it is most efficient for the submit branch to be a local mirror.
5114
    If a public location is known for the submit_branch, that location is used
5115
    in the merge directive.
5116
5117
    The default behaviour is to send the merge directive by mail, unless -o is
5118
    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.
5119
5120
    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
5121
    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.
5122
    If the preferred client can't be found (or used), your editor will be used.
5123
5124
    To use a specific mail program, set the mail_client configuration option.
5125
    (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
5126
    specific clients are "claws", "evolution", "kmail", "mail.app" (MacOS X's
5127
    Mail.app), "mutt", and "thunderbird"; generic options are "default",
5128
    "editor", "emacsclient", "mapi", and "xdg-email".  Plugins may also add
5129
    supported clients.
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5130
5131
    If mail is being sent, a to address is required.  This can be supplied
5132
    either on the commandline, by setting the submit_to configuration
5133
    option in the branch itself or the child_submit_to configuration option
5134
    in the submit branch.
5135
5136
    Two formats are currently supported: "4" uses revision bundle format 4 and
5137
    merge directive format 2.  It is significantly faster and smaller than
5138
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
5139
    default.  "0.9" uses revision bundle format 0.9 and merge directive
5140
    format 1.  It is compatible with Bazaar 0.12 - 0.18.
5141
5142
    The merge directives created by bzr send may be applied using bzr merge or
5143
    bzr pull by specifying a file containing a merge directive as the location.
4949.2.1 by Martin Pool
Better help for cmd_send
5144
5145
    bzr send makes extensive use of public locations to map local locations into
5146
    URLs that can be used by other people.  See `bzr help configuration` to
5147
    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.
5148
    """
5149
5150
    encoding_type = 'exact'
5151
5152
    _see_also = ['merge', 'pull']
5153
5154
    takes_args = ['submit_branch?', 'public_branch?']
5155
5156
    takes_options = [
5157
        Option('no-bundle',
5158
               help='Do not include a bundle in the merge directive.'),
5159
        Option('no-patch', help='Do not include a preview patch in the merge'
5160
               ' directive.'),
5161
        Option('remember',
5162
               help='Remember submit and public branch.'),
5163
        Option('from',
5164
               help='Branch to generate the submission from, '
5165
               'rather than the one containing the working directory.',
5166
               short_name='f',
5167
               type=unicode),
5168
        Option('output', short_name='o',
5086.3.3 by Jelmer Vernooij
Allow merge directives to output multiple patch files.
5169
               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.
5170
                    'use - for stdout.',
5171
               type=unicode),
4464.3.4 by Vincent Ladeuil
Fix bug #206577 by adding a --strict option to send.
5172
        Option('strict',
5173
               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.
5174
               ' 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.
5175
        Option('mail-to', help='Mail the request to this address.',
5176
               type=unicode),
5177
        'revision',
5178
        'message',
5179
        Option('body', help='Body for the email.', type=unicode),
5180
        RegistryOption('format',
4464.3.4 by Vincent Ladeuil
Fix bug #206577 by adding a --strict option to send.
5181
                       help='Use the specified output format.',
5182
                       lazy_registry=('bzrlib.send', 'format_registry')),
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5183
        ]
5184
5185
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5186
            no_patch=False, revision=None, remember=False, output=None,
4464.3.4 by Vincent Ladeuil
Fix bug #206577 by adding a --strict option to send.
5187
            format=None, mail_to=None, message=None, body=None,
5188
            strict=None, **kwargs):
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5189
        from bzrlib.send import send
5190
        return send(submit_branch, revision, public_branch, remember,
4464.3.4 by Vincent Ladeuil
Fix bug #206577 by adding a --strict option to send.
5191
                    format, no_bundle, no_patch, output,
5192
                    kwargs.get('from', '.'), mail_to, message, body,
5193
                    self.outf,
5194
                    strict=strict)
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5195
5196
4367.1.6 by Jelmer Vernooij
Fix bundle revisions.
5197
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
5198
    __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.
5199
5200
    A merge directive provides many things needed for requesting merges:
5201
5202
    * A machine-readable description of the merge to perform
5203
5204
    * An optional patch that is a preview of the changes requested
5205
5206
    * An optional bundle of revision data, so that the changes can be applied
5207
      directly from the merge directive, without retrieving data from a
5208
      branch.
5209
5210
    If --no-bundle is specified, then public_branch is needed (and must be
5211
    up-to-date), so that the receiver can perform the merge using the
5212
    public_branch.  The public_branch is always included if known, so that
5213
    people can check it later.
5214
5215
    The submit branch defaults to the parent, but can be overridden.  Both
5216
    submit branch and public branch will be remembered if supplied.
5217
5218
    If a public_branch is known for the submit_branch, that public submit
5219
    branch is used in the merge instructions.  This means that a local mirror
5220
    can be used as your actual submit branch, once you have set public_branch
5221
    for that mirror.
5222
5223
    Two formats are currently supported: "4" uses revision bundle format 4 and
5224
    merge directive format 2.  It is significantly faster and smaller than
5225
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
5226
    default.  "0.9" uses revision bundle format 0.9 and merge directive
5227
    format 1.  It is compatible with Bazaar 0.12 - 0.18.
5228
    """
5229
5230
    takes_options = [
5231
        Option('no-bundle',
5232
               help='Do not include a bundle in the merge directive.'),
5233
        Option('no-patch', help='Do not include a preview patch in the merge'
5234
               ' directive.'),
5235
        Option('remember',
5236
               help='Remember submit and public branch.'),
5237
        Option('from',
5238
               help='Branch to generate the submission from, '
5239
               'rather than the one containing the working directory.',
5240
               short_name='f',
5241
               type=unicode),
5242
        Option('output', short_name='o', help='Write directive to this file.',
5243
               type=unicode),
4464.3.6 by Vincent Ladeuil
bundle-revisions should support --strict too.
5244
        Option('strict',
4464.3.11 by Vincent Ladeuil
Add a check for tree/branch sync and tweak help.
5245
               help='Refuse to bundle revisions if there are uncommitted'
5246
               ' 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.
5247
        'revision',
5248
        RegistryOption('format',
5249
                       help='Use the specified output format.',
5250
                       lazy_registry=('bzrlib.send', 'format_registry')),
5251
        ]
5252
    aliases = ['bundle']
5253
5254
    _see_also = ['send', 'merge']
5255
5256
    hidden = True
5257
5258
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
5259
            no_patch=False, revision=None, remember=False, output=None,
4464.3.6 by Vincent Ladeuil
bundle-revisions should support --strict too.
5260
            format=None, strict=None, **kwargs):
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5261
        if output is None:
5262
            output = '-'
5263
        from bzrlib.send import send
5264
        return send(submit_branch, revision, public_branch, remember,
5265
                         format, no_bundle, no_patch, output,
5266
                         kwargs.get('from', '.'), None, None, None,
4464.3.6 by Vincent Ladeuil
bundle-revisions should support --strict too.
5267
                         self.outf, strict=strict)
4367.1.3 by Jelmer Vernooij
Move cmd_{send,bundle_revisions} back to bzrlib.builtins per Ians request.
5268
5269
2220.2.2 by Martin Pool
Add tag command and basic implementation
5270
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
5271
    __doc__ = """Create, remove or modify a tag naming a revision.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
5272
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
5273
    Tags give human-meaningful names to revisions.  Commands that take a -r
5274
    (--revision) option can be given -rtag:X, where X is any previously
5275
    created tag.
5276
2220.2.41 by Martin Pool
Fix tag help (fullermd)
5277
    Tags are stored in the branch.  Tags are copied from one branch to another
5278
    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.
5279
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
5280
    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.
5281
    --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
5282
3566.2.2 by Benjamin Peterson
fix markup
5283
    To rename a tag (change the name but keep it on the same revsion), run ``bzr
5284
    tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
5086.4.9 by Jelmer Vernooij
Update documentation.
5285
5286
    If no tag name is specified it will be determined through the 
5287
    'automatic_tag_name' hook. This can e.g. be used to automatically tag
5288
    upstream releases by reading configure.ac. See ``bzr help hooks`` for
5289
    details.
2220.2.8 by Martin Pool
Add -d option to push, pull, merge commands.
5290
    """
2220.2.2 by Martin Pool
Add tag command and basic implementation
5291
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
5292
    _see_also = ['commit', 'tags']
5086.4.2 by Jelmer Vernooij
Tag names can now be determined automatically by hooks if they are
5293
    takes_args = ['tag_name?']
2220.2.2 by Martin Pool
Add tag command and basic implementation
5294
    takes_options = [
2220.2.21 by Martin Pool
Add tag --delete command and implementation
5295
        Option('delete',
2220.2.42 by Martin Pool
Tag command refuses to replace existing tags unless you force it.
5296
            help='Delete this tag rather than placing it.',
5297
            ),
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
5298
        custom_help('directory',
5299
            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.
5300
        Option('force',
2598.1.2 by Martin Pool
Also check that option help ends in a period, and fix those that don't
5301
            help='Replace existing tags.',
2220.2.21 by Martin Pool
Add tag --delete command and implementation
5302
            ),
2220.2.6 by Martin Pool
Add tag -r option
5303
        'revision',
2220.2.2 by Martin Pool
Add tag command and basic implementation
5304
        ]
5305
5086.4.2 by Jelmer Vernooij
Tag names can now be determined automatically by hooks if they are
5306
    def run(self, tag_name=None,
2220.2.42 by Martin Pool
Tag command refuses to replace existing tags unless you force it.
5307
            delete=None,
5308
            directory='.',
5309
            force=None,
2220.2.21 by Martin Pool
Add tag --delete command and implementation
5310
            revision=None,
2220.2.42 by Martin Pool
Tag command refuses to replace existing tags unless you force it.
5311
            ):
2220.2.2 by Martin Pool
Add tag command and basic implementation
5312
        branch, relpath = Branch.open_containing(directory)
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
5313
        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.
5314
        if delete:
5086.4.2 by Jelmer Vernooij
Tag names can now be determined automatically by hooks if they are
5315
            if tag_name is None:
5316
                raise errors.BzrCommandError("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.
5317
            branch.tags.delete_tag(tag_name)
5318
            self.outf.write('Deleted tag %s.\n' % tag_name)
5319
        else:
5320
            if revision:
5321
                if len(revision) != 1:
5322
                    raise errors.BzrCommandError(
5323
                        "Tags can only be placed on a single revision, "
5324
                        "not on a range")
5325
                revision_id = revision[0].as_revision_id(branch)
2220.2.21 by Martin Pool
Add tag --delete command and implementation
5326
            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.
5327
                revision_id = branch.last_revision()
5086.4.2 by Jelmer Vernooij
Tag names can now be determined automatically by hooks if they are
5328
            if tag_name is None:
5086.4.7 by Jelmer Vernooij
Put automatic_tag_name on Branch.
5329
                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
5330
                if tag_name is None:
5331
                    raise errors.BzrCommandError(
5332
                        "Please specify a 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.
5333
            if (not force) and branch.tags.has_tag(tag_name):
5334
                raise errors.TagAlreadyExists(tag_name)
5335
            branch.tags.set_tag(tag_name, revision_id)
5336
            self.outf.write('Created tag %s.\n' % tag_name)
2220.2.2 by Martin Pool
Add tag command and basic implementation
5337
5338
2220.2.24 by Martin Pool
Add tags command
5339
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
5340
    __doc__ = """List tags.
2220.2.24 by Martin Pool
Add tags command
5341
3007.1.1 by Adeodato Simó
Small fix to tags' help.
5342
    This command shows a table of tag names and the revisions they reference.
2220.2.24 by Martin Pool
Add tags command
5343
    """
5344
2425.2.3 by Robert Collins
Update existing builtin commands help text to use _see_also. (Robert Collins)
5345
    _see_also = ['tag']
2220.2.24 by Martin Pool
Add tags command
5346
    takes_options = [
5171.3.1 by Martin von Gagern
Turn --directory and -d into a global option.
5347
        custom_help('directory',
5348
            help='Branch whose tags should be displayed.'),
2805.8.6 by Adeodato Simó
Don't sort by revno; only by time if --sort=time is passed.
5349
        RegistryOption.from_kwargs('sort',
5350
            'Sort tags by different criteria.', title='Sorting',
5351
            alpha='Sort tags lexicographically (default).',
5352
            time='Sort tags chronologically.',
5353
            ),
2805.8.3 by Adeodato Simó
Show dotted revnos, and revids only with --show-ids.
5354
        '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.
5355
        'revision',
2220.2.24 by Martin Pool
Add tags command
5356
    ]
5357
5358
    @display_command
5359
    def run(self,
5360
            directory='.',
2805.8.6 by Adeodato Simó
Don't sort by revno; only by time if --sort=time is passed.
5361
            sort='alpha',
2805.8.3 by Adeodato Simó
Show dotted revnos, and revids only with --show-ids.
5362
            show_ids=False,
3904.2.1 by Marius Kruger
* factor out _get2Revisions from cmd_log to be able to reuse how revesions is determined by log.
5363
            revision=None,
2220.2.24 by Martin Pool
Add tags command
5364
            ):
5365
        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.
5366
2805.8.6 by Adeodato Simó
Don't sort by revno; only by time if --sort=time is passed.
5367
        tags = branch.tags.get_tag_dict().items()
3553.1.1 by Robert Collins
Do not scan history for tags when none are present.
5368
        if not tags:
5369
            return
3904.2.1 by Marius Kruger
* factor out _get2Revisions from cmd_log to be able to reuse how revesions is determined by log.
5370
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
5371
        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.
5372
        if revision:
5373
            graph = branch.repository.get_graph()
5374
            rev1, rev2 = _get_revision_range(revision, branch, self.name())
5375
            revid1, revid2 = rev1.rev_id, rev2.rev_id
5376
            # only show revisions between revid1 and revid2 (inclusive)
5377
            tags = [(tag, revid) for tag, revid in tags if
5378
                graph.is_between(revid, revid1, revid2)]
5379
        if sort == 'alpha':
5380
            tags.sort()
5381
        elif sort == 'time':
5382
            timestamps = {}
5383
            for tag, revid in tags:
5384
                try:
5385
                    revobj = branch.repository.get_revision(revid)
5386
                except errors.NoSuchRevision:
5387
                    timestamp = sys.maxint # place them at the end
5388
                else:
5389
                    timestamp = revobj.timestamp
5390
                timestamps[revid] = timestamp
5391
            tags.sort(key=lambda x: timestamps[x[1]])
5392
        if not show_ids:
5393
            # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
5394
            for index, (tag, revid) in enumerate(tags):
5395
                try:
5396
                    revno = branch.revision_id_to_dotted_revno(revid)
5397
                    if isinstance(revno, tuple):
5398
                        revno = '.'.join(map(str, revno))
5399
                except errors.NoSuchRevision:
5400
                    # Bad tag data/merges can lead to tagged revisions
5401
                    # which are not in this branch. Fail gracefully ...
5402
                    revno = '?'
5403
                tags[index] = (tag, revno)
5404
        self.cleanup_now()
2805.8.6 by Adeodato Simó
Don't sort by revno; only by time if --sort=time is passed.
5405
        for tag, revspec in tags:
5406
            self.outf.write('%-20s %s\n' % (tag, revspec))
2220.2.24 by Martin Pool
Add tags command
5407
5408
2796.2.5 by Aaron Bentley
Implement reconfigure command
5409
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
5410
    __doc__ = """Reconfigure the type of a bzr directory.
2796.2.15 by Aaron Bentley
More updates from review
5411
5412
    A target configuration must be specified.
5413
5414
    For checkouts, the bind-to location will be auto-detected if not specified.
5415
    The order of preference is
5416
    1. For a lightweight checkout, the current bound location.
5417
    2. For branches that used to be checkouts, the previously-bound location.
5418
    3. The push location.
5419
    4. The parent location.
5420
    If none of these is available, --bind-to must be specified.
5421
    """
2796.2.5 by Aaron Bentley
Implement reconfigure command
5422
3535.4.1 by Marius Kruger
Update reconfigure help to say exactly what it wil do.
5423
    _see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
2796.2.5 by Aaron Bentley
Implement reconfigure command
5424
    takes_args = ['location?']
3983.3.11 by Vincent Ladeuil
Fix indentation as per Aaron's review and then some.
5425
    takes_options = [
5426
        RegistryOption.from_kwargs(
5427
            'target_type',
5428
            title='Target type',
5429
            help='The type to reconfigure the directory to.',
5430
            value_switches=True, enum_switch=False,
5431
            branch='Reconfigure to be an unbound branch with no working tree.',
5432
            tree='Reconfigure to be an unbound branch with a working tree.',
5433
            checkout='Reconfigure to be a bound branch with a working tree.',
5434
            lightweight_checkout='Reconfigure to be a lightweight'
5435
                ' checkout (with no local history).',
5436
            standalone='Reconfigure to be a standalone branch '
5437
                '(i.e. stop using shared repository).',
5438
            use_shared='Reconfigure to use a shared repository.',
5439
            with_trees='Reconfigure repository to create '
5440
                'working trees on branches by default.',
5441
            with_no_trees='Reconfigure repository to not create '
5442
                'working trees on branches by default.'
5443
            ),
5444
        Option('bind-to', help='Branch to bind checkout to.', type=str),
5445
        Option('force',
4509.3.1 by Martin Pool
Initial failing test for 'reconfigure --stacked-on'
5446
            help='Perform reconfiguration even if local changes'
5447
            ' will be lost.'),
5448
        Option('stacked-on',
4509.3.3 by Martin Pool
Add reconfigure --unstacked command
5449
            help='Reconfigure a branch to be stacked on another branch.',
4509.3.1 by Martin Pool
Initial failing test for 'reconfigure --stacked-on'
5450
            type=unicode,
5451
            ),
4509.3.3 by Martin Pool
Add reconfigure --unstacked command
5452
        Option('unstacked',
5453
            help='Reconfigure a branch to be unstacked.  This '
4509.3.34 by Martin Pool
Fix typo
5454
                'may require copying substantial data into it.',
4509.3.3 by Martin Pool
Add reconfigure --unstacked command
5455
            ),
3983.3.11 by Vincent Ladeuil
Fix indentation as per Aaron's review and then some.
5456
        ]
2796.2.5 by Aaron Bentley
Implement reconfigure command
5457
4509.3.1 by Martin Pool
Initial failing test for 'reconfigure --stacked-on'
5458
    def run(self, location=None, target_type=None, bind_to=None, force=False,
4509.3.3 by Martin Pool
Add reconfigure --unstacked command
5459
            stacked_on=None,
5460
            unstacked=None):
2796.2.5 by Aaron Bentley
Implement reconfigure command
5461
        directory = bzrdir.BzrDir.open(location)
4509.3.35 by Martin Pool
Ban reconfigure --stacked-on foo --unstacked
5462
        if stacked_on and unstacked:
5463
            raise BzrCommandError("Can't use both --stacked-on and --unstacked")
5464
        elif stacked_on is not None:
4509.3.38 by Martin Pool
Move reconfigure --stacked-on core code into reconfigure.py
5465
            reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
4509.3.3 by Martin Pool
Add reconfigure --unstacked command
5466
        elif unstacked:
4509.3.39 by Martin Pool
Move reconfigure --unstacked to reconfigure.py
5467
            reconfigure.ReconfigureUnstacked().apply(directory)
4509.3.1 by Martin Pool
Initial failing test for 'reconfigure --stacked-on'
5468
        # At the moment you can use --stacked-on and a different
5469
        # reconfiguration shape at the same time; there seems no good reason
5470
        # to ban it.
2796.2.15 by Aaron Bentley
More updates from review
5471
        if target_type is None:
4509.3.3 by Martin Pool
Add reconfigure --unstacked command
5472
            if stacked_on or unstacked:
4509.3.1 by Martin Pool
Initial failing test for 'reconfigure --stacked-on'
5473
                return
5474
            else:
4509.3.22 by Martin Pool
Fix typo in reconfigure error message
5475
                raise errors.BzrCommandError('No target configuration '
4509.3.1 by Martin Pool
Initial failing test for 'reconfigure --stacked-on'
5476
                    'specified')
2796.2.15 by Aaron Bentley
More updates from review
5477
        elif target_type == 'branch':
2796.2.5 by Aaron Bentley
Implement reconfigure command
5478
            reconfiguration = reconfigure.Reconfigure.to_branch(directory)
5479
        elif target_type == 'tree':
5480
            reconfiguration = reconfigure.Reconfigure.to_tree(directory)
5481
        elif target_type == 'checkout':
3983.3.11 by Vincent Ladeuil
Fix indentation as per Aaron's review and then some.
5482
            reconfiguration = reconfigure.Reconfigure.to_checkout(
5483
                directory, bind_to)
2796.2.19 by Aaron Bentley
Support reconfigure --lightweight-checkout
5484
        elif target_type == 'lightweight-checkout':
5485
            reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
5486
                directory, bind_to)
3311.2.6 by Aaron Bentley
rename 'sharing' to 'use-shared'
5487
        elif target_type == 'use-shared':
5488
            reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
3311.2.5 by Aaron Bentley
Implement reconfigure --standalone and --sharing
5489
        elif target_type == 'standalone':
5490
            reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
3921.4.3 by Matthew Fuller
Add --with-trees and --with-no-trees to the 'reconfigure' command.
5491
        elif target_type == 'with-trees':
5492
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5493
                directory, True)
5494
        elif target_type == 'with-no-trees':
5495
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
5496
                directory, False)
2796.2.5 by Aaron Bentley
Implement reconfigure command
5497
        reconfiguration.apply(force)
5498
5499
2999.1.1 by Ian Clatworthy
migrate switch command into the core - was in BzrTools
5500
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
5501
    __doc__ = """Set the branch of a checkout and update.
3943.8.1 by Marius Kruger
remove all trailing whitespace from bzr source
5502
3078.2.2 by Ian Clatworthy
get switch tests passing on heavyweight checkouts
5503
    For lightweight checkouts, this changes the branch being referenced.
5504
    For heavyweight checkouts, this checks that there are no local commits
5505
    versus the current bound branch, then it makes the local branch a mirror
5506
    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.
5507
3078.2.2 by Ian Clatworthy
get switch tests passing on heavyweight checkouts
5508
    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.
5509
    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
5510
5511
    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
5512
5513
    The path to the branch to switch to can be specified relative to the parent
5514
    directory of the current branch. For example, if you are currently in a
5515
    checkout of /path/to/branch, specifying 'newbranch' will find a branch at
5516
    /path/to/newbranch.
3565.6.15 by Marius Kruger
update bind and switch command descriptions to state what will happen to nicknames.
5517
3565.6.16 by Marius Kruger
update nick command description to mention how it works for bound branches,
5518
    Bound branches use the nickname of its master branch unless it is set
4775.1.1 by Martin Pool
Remove several 'the the' typos
5519
    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.
5520
    that of the master.
3078.2.2 by Ian Clatworthy
get switch tests passing on heavyweight checkouts
5521
    """
2999.1.1 by Ian Clatworthy
migrate switch command into the core - was in BzrTools
5522
3984.5.11 by Daniel Watkins
Allow only a revision to be passed to switch.
5523
    takes_args = ['to_location?']
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
5524
    takes_options = ['directory',
5525
                     Option('force',
3984.5.5 by Daniel Watkins
bzr switch now takes a revision option.
5526
                        help='Switch even if local commits will be lost.'),
3984.5.19 by Andrew Bennetts
Merge lp:bzr, resolving conflicts.
5527
                     'revision',
4520.1.1 by John Arbash Meinel
'bzr switch -b' can now be used to create the branch while you switch to it.
5528
                     Option('create-branch', short_name='b',
5529
                        help='Create the target branch from this one before'
5530
                             ' switching to it.'),
3984.5.19 by Andrew Bennetts
Merge lp:bzr, resolving conflicts.
5531
                    ]
2999.1.1 by Ian Clatworthy
migrate switch command into the core - was in BzrTools
5532
3984.5.19 by Andrew Bennetts
Merge lp:bzr, resolving conflicts.
5533
    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.
5534
            revision=None, directory=u'.'):
2999.1.2 by Ian Clatworthy
incorporate review feedback including basic blackbox tests
5535
        from bzrlib import switch
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
5536
        tree_location = directory
3984.5.18 by Daniel Watkins
cmd_switch now uses _get_one_revision.
5537
        revision = _get_one_revision('switch', revision)
2999.1.2 by Ian Clatworthy
incorporate review feedback including basic blackbox tests
5538
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
3984.5.11 by Daniel Watkins
Allow only a revision to be passed to switch.
5539
        if to_location is None:
5540
            if revision is None:
5541
                raise errors.BzrCommandError('You must supply either a'
5542
                                             ' revision or a location')
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
5543
            to_location = tree_location
4354.2.1 by Aaron Bentley
Improve switch --force with lightweight checkouts.
5544
        try:
5545
            branch = control_dir.open_branch()
5546
            had_explicit_nick = branch.get_config().has_explicit_nickname()
5547
        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.
5548
            branch = None
4354.2.1 by Aaron Bentley
Improve switch --force with lightweight checkouts.
5549
            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.
5550
        if create_branch:
5551
            if branch is None:
5552
                raise errors.BzrCommandError('cannot create branch without'
5553
                                             ' source branch')
4879.2.1 by Neil Martinsen-Burrell
switch should use directory services when creating a branch
5554
            to_location = directory_service.directories.dereference(
5555
                              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.
5556
            if '/' not in to_location and '\\' not in to_location:
5557
                # This path is meant to be relative to the existing branch
5558
                this_url = self._get_branch_location(control_dir)
5559
                to_location = urlutils.join(this_url, '..', to_location)
5560
            to_branch = branch.bzrdir.sprout(to_location,
5561
                                 possible_transports=[branch.bzrdir.root_transport],
5562
                                 source_branch=branch).open_branch()
5563
        else:
5564
            try:
5565
                to_branch = Branch.open(to_location)
5566
            except errors.NotBranchError:
5567
                this_url = self._get_branch_location(control_dir)
5568
                to_branch = Branch.open(
5569
                    urlutils.join(this_url, '..', to_location))
3984.5.13 by Daniel Watkins
Changed switch and cmd_switch to reflect change back.
5570
        if revision is not None:
3984.5.18 by Daniel Watkins
cmd_switch now uses _get_one_revision.
5571
            revision = revision.as_revision_id(to_branch)
3984.5.19 by Andrew Bennetts
Merge lp:bzr, resolving conflicts.
5572
        switch.switch(control_dir, to_branch, force, revision_id=revision)
4354.2.1 by Aaron Bentley
Improve switch --force with lightweight checkouts.
5573
        if had_explicit_nick:
3565.6.7 by Marius Kruger
* checkouts now use master nick when no explicit nick is set.
5574
            branch = control_dir.open_branch() #get the new branch!
5575
            branch.nick = to_branch.nick
2999.1.1 by Ian Clatworthy
migrate switch command into the core - was in BzrTools
5576
        note('Switched to branch: %s',
5577
            urlutils.unescape_for_display(to_branch.base, 'utf-8'))
5578
4354.2.1 by Aaron Bentley
Improve switch --force with lightweight checkouts.
5579
    def _get_branch_location(self, control_dir):
5580
        """Return location of branch for this control dir."""
5581
        try:
5582
            this_branch = control_dir.open_branch()
5583
            # 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.
5584
            master_location = this_branch.get_bound_location()
5585
            if master_location is not None:
5586
                return master_location
4354.2.1 by Aaron Bentley
Improve switch --force with lightweight checkouts.
5587
            # If not, use a local sibling
5588
            return this_branch.base
5589
        except errors.NotBranchError:
5590
            format = control_dir.find_branch_format()
5591
            if getattr(format, 'get_reference', None) is not None:
5592
                return format.get_reference(control_dir)
5593
            else:
5594
                return control_dir.root_transport.base
5595
2999.1.1 by Ian Clatworthy
migrate switch command into the core - was in BzrTools
5596
3586.1.9 by Ian Clatworthy
first cut at view command
5597
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
5598
    __doc__ = """Manage filtered views.
3586.1.33 by Ian Clatworthy
cleanup trailing whitespace
5599
3586.1.9 by Ian Clatworthy
first cut at view command
5600
    Views provide a mask over the tree so that users can focus on
5601
    a subset of a tree when doing their work. After creating a view,
5602
    commands that support a list of files - status, diff, commit, etc -
5603
    effectively have that list of files implicitly given each time.
5604
    An explicit list of files can still be given but those files
5605
    must be within the current view.
5606
5607
    In most cases, a view has a short life-span: it is created to make
5608
    a selected change and is deleted once that change is committed.
5609
    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
5610
    and switch between them.
3586.1.33 by Ian Clatworthy
cleanup trailing whitespace
5611
3586.1.9 by Ian Clatworthy
first cut at view command
5612
    To disable the current view without deleting it, you can switch to
5613
    the pseudo view called ``off``. This can be useful when you need
5614
    to see the whole tree for an operation or two (e.g. merge) but
5615
    want to switch back to your view after that.
5616
5617
    :Examples:
3586.1.14 by Ian Clatworthy
added --all option to the view command
5618
      To define the current view::
3586.1.9 by Ian Clatworthy
first cut at view command
5619
5620
        bzr view file1 dir1 ...
5621
5622
      To list the current view::
5623
5624
        bzr view
5625
5626
      To delete the current view::
5627
5628
        bzr view --delete
5629
5630
      To disable the current view without deleting it::
5631
5632
        bzr view --switch off
5633
3586.1.14 by Ian Clatworthy
added --all option to the view command
5634
      To define a named view and switch to it::
3586.1.9 by Ian Clatworthy
first cut at view command
5635
5636
        bzr view --name view-name file1 dir1 ...
5637
5638
      To list a named view::
5639
5640
        bzr view --name view-name
5641
5642
      To delete a named view::
5643
5644
        bzr view --name view-name --delete
5645
5646
      To switch to a named view::
5647
5648
        bzr view --switch view-name
3586.1.14 by Ian Clatworthy
added --all option to the view command
5649
5650
      To list all views defined::
5651
5652
        bzr view --all
5653
5654
      To delete all views::
5655
5656
        bzr view --delete --all
3586.1.9 by Ian Clatworthy
first cut at view command
5657
    """
5658
3586.1.14 by Ian Clatworthy
added --all option to the view command
5659
    _see_also = []
3586.1.9 by Ian Clatworthy
first cut at view command
5660
    takes_args = ['file*']
5661
    takes_options = [
3586.1.14 by Ian Clatworthy
added --all option to the view command
5662
        Option('all',
5663
            help='Apply list or delete action to all views.',
5664
            ),
3586.1.9 by Ian Clatworthy
first cut at view command
5665
        Option('delete',
5666
            help='Delete the view.',
5667
            ),
5668
        Option('name',
3586.1.14 by Ian Clatworthy
added --all option to the view command
5669
            help='Name of the view to define, list or delete.',
3586.1.9 by Ian Clatworthy
first cut at view command
5670
            type=unicode,
5671
            ),
5672
        Option('switch',
5673
            help='Name of the view to switch to.',
5674
            type=unicode,
5675
            ),
5676
        ]
5677
5678
    def run(self, file_list,
3586.1.14 by Ian Clatworthy
added --all option to the view command
5679
            all=False,
3586.1.9 by Ian Clatworthy
first cut at view command
5680
            delete=False,
5681
            name=None,
5682
            switch=None,
5683
            ):
5346.4.5 by Martin Pool
Deprecate and avoid internal_tree_files and tree_files.
5684
        tree, file_list = WorkingTree.open_containing_paths(file_list,
5685
            apply_view=False)
3586.1.9 by Ian Clatworthy
first cut at view command
5686
        current_view, view_dict = tree.views.get_view_info()
5687
        if name is None:
5688
            name = current_view
5689
        if delete:
5690
            if file_list:
3586.1.11 by Ian Clatworthy
tweak user feedback
5691
                raise errors.BzrCommandError(
5692
                    "Both --delete and a file list specified")
3586.1.9 by Ian Clatworthy
first cut at view command
5693
            elif switch:
3586.1.11 by Ian Clatworthy
tweak user feedback
5694
                raise errors.BzrCommandError(
5695
                    "Both --delete and --switch specified")
3586.1.14 by Ian Clatworthy
added --all option to the view command
5696
            elif all:
5697
                tree.views.set_view_info(None, {})
5698
                self.outf.write("Deleted all views.\n")
3586.1.9 by Ian Clatworthy
first cut at view command
5699
            elif name is None:
3586.1.11 by Ian Clatworthy
tweak user feedback
5700
                raise errors.BzrCommandError("No current view to delete")
3586.1.9 by Ian Clatworthy
first cut at view command
5701
            else:
5702
                tree.views.delete_view(name)
5703
                self.outf.write("Deleted '%s' view.\n" % name)
5704
        elif switch:
5705
            if file_list:
3586.1.11 by Ian Clatworthy
tweak user feedback
5706
                raise errors.BzrCommandError(
5707
                    "Both --switch and a file list specified")
3586.1.14 by Ian Clatworthy
added --all option to the view command
5708
            elif all:
5709
                raise errors.BzrCommandError(
5710
                    "Both --switch and --all specified")
3586.1.9 by Ian Clatworthy
first cut at view command
5711
            elif switch == 'off':
5712
                if current_view is None:
3586.1.11 by Ian Clatworthy
tweak user feedback
5713
                    raise errors.BzrCommandError("No current view to disable")
3586.1.9 by Ian Clatworthy
first cut at view command
5714
                tree.views.set_view_info(None, view_dict)
3586.1.11 by Ian Clatworthy
tweak user feedback
5715
                self.outf.write("Disabled '%s' view.\n" % (current_view))
3586.1.9 by Ian Clatworthy
first cut at view command
5716
            else:
5717
                tree.views.set_view_info(switch, view_dict)
3586.1.20 by Ian Clatworthy
centralise formatting of view file lists
5718
                view_str = views.view_display_str(tree.views.lookup_view())
5719
                self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
3586.1.14 by Ian Clatworthy
added --all option to the view command
5720
        elif all:
5721
            if view_dict:
5722
                self.outf.write('Views defined:\n')
5723
                for view in sorted(view_dict):
5724
                    if view == current_view:
5725
                        active = "=>"
5726
                    else:
5727
                        active = "  "
3586.1.20 by Ian Clatworthy
centralise formatting of view file lists
5728
                    view_str = views.view_display_str(view_dict[view])
5729
                    self.outf.write('%s %-20s %s\n' % (active, view, view_str))
3586.1.14 by Ian Clatworthy
added --all option to the view command
5730
            else:
5731
                self.outf.write('No views defined.\n')
3586.1.9 by Ian Clatworthy
first cut at view command
5732
        elif file_list:
5733
            if name is None:
5734
                # No name given and no current view set
5735
                name = 'my'
5736
            elif name == 'off':
3586.1.11 by Ian Clatworthy
tweak user feedback
5737
                raise errors.BzrCommandError(
5738
                    "Cannot change the 'off' pseudo view")
3586.1.9 by Ian Clatworthy
first cut at view command
5739
            tree.views.set_view(name, sorted(file_list))
3586.1.20 by Ian Clatworthy
centralise formatting of view file lists
5740
            view_str = views.view_display_str(tree.views.lookup_view())
3586.1.11 by Ian Clatworthy
tweak user feedback
5741
            self.outf.write("Using '%s' view: %s\n" % (name, view_str))
3586.1.9 by Ian Clatworthy
first cut at view command
5742
        else:
5743
            # list the files
3586.1.13 by Ian Clatworthy
fix list of a known view when no current view set
5744
            if name is None:
5745
                # No name given and no current view set
3586.1.9 by Ian Clatworthy
first cut at view command
5746
                self.outf.write('No current view.\n')
5747
            else:
3586.1.20 by Ian Clatworthy
centralise formatting of view file lists
5748
                view_str = views.view_display_str(tree.views.lookup_view(name))
3586.1.11 by Ian Clatworthy
tweak user feedback
5749
                self.outf.write("'%s' view is: %s\n" % (name, view_str))
3586.1.9 by Ian Clatworthy
first cut at view command
5750
5751
3254.2.1 by Daniel Watkins
Added cmd_hooks.
5752
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
5753
    __doc__ = """Show hooks."""
3254.2.1 by Daniel Watkins
Added cmd_hooks.
5754
3254.2.9 by Daniel Watkins
Made cmd_hooks hidden.
5755
    hidden = True
3254.2.1 by Daniel Watkins
Added cmd_hooks.
5756
4119.3.2 by Robert Collins
Migrate existing hooks over to the new HookPoint infrastructure.
5757
    def run(self):
5758
        for hook_key in sorted(hooks.known_hooks.keys()):
5759
            some_hooks = hooks.known_hooks_key_to_object(hook_key)
5760
            self.outf.write("%s:\n" % type(some_hooks).__name__)
5761
            for hook_name, hook_point in sorted(some_hooks.items()):
5762
                self.outf.write("  %s:\n" % (hook_name,))
5763
                found_hooks = list(hook_point)
5764
                if found_hooks:
5765
                    for hook in found_hooks:
5766
                        self.outf.write("    %s\n" %
5767
                                        (some_hooks.get_hook_name(hook),))
5768
                else:
5769
                    self.outf.write("    <no hooks installed>\n")
3254.2.1 by Daniel Watkins
Added cmd_hooks.
5770
5771
4991.1.3 by Jelmer Vernooij
Name command remove-branch, rmbranch as alias.
5772
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
5773
    __doc__ = """Remove a branch.
4991.1.1 by Jelmer Vernooij
Add rmbranch command.
5774
4991.1.5 by Jelmer Vernooij
Add example for rmbranch, explain a bit better what the command does.
5775
    This will remove the branch from the specified location but 
4991.1.6 by Jelmer Vernooij
Docstring tweaks from Ians review.
5776
    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.
5777
5778
    :Examples:
5779
4991.1.6 by Jelmer Vernooij
Docstring tweaks from Ians review.
5780
      Remove the branch at repo/trunk::
4991.1.5 by Jelmer Vernooij
Add example for rmbranch, explain a bit better what the command does.
5781
5782
        bzr remove-branch repo/trunk
5783
4991.1.1 by Jelmer Vernooij
Add rmbranch command.
5784
    """
5785
5786
    takes_args = ["location?"]
5787
4991.1.3 by Jelmer Vernooij
Name command remove-branch, rmbranch as alias.
5788
    aliases = ["rmbranch"]
5789
4991.1.1 by Jelmer Vernooij
Add rmbranch command.
5790
    def run(self, location=None):
5791
        if location is None:
5792
            location = "."
5793
        branch = Branch.open_containing(location)[0]
5794
        branch.bzrdir.destroy_branch()
5795
        
5796
0.16.80 by Aaron Bentley
Rename shelve2/unshelve2 to shelve/unshelve
5797
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
5798
    __doc__ = """Temporarily set aside some changes from the current tree.
0.16.74 by Aaron Bentley
Merge with shelf-manager
5799
5800
    Shelve allows you to temporarily put changes you've made "on the shelf",
5801
    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.
5802
    the shelf with the 'unshelve' command.  The changes are stored alongside
5803
    your working tree, and so they aren't propagated along with your branch nor
5804
    will they survive its deletion.
0.16.74 by Aaron Bentley
Merge with shelf-manager
5805
0.16.113 by Aaron Bentley
Change ls-shelf to shelve --list
5806
    If shelve --list is specified, previously-shelved changes are listed.
5807
0.16.74 by Aaron Bentley
Merge with shelf-manager
5808
    Shelve is intended to help separate several sets of changes that have
5809
    been inappropriately mingled.  If you just want to get rid of all changes
5810
    and you don't need to restore them later, use revert.  If you want to
5811
    shelve all text changes at once, use shelve --all.
5812
5813
    If filenames are specified, only the changes to those files will be
5814
    shelved. Other files will be left untouched.
5815
5816
    If a revision is specified, changes since that revision will be shelved.
5817
5818
    You can put multiple items on the shelf, and by default, 'unshelve' will
5819
    restore the most recently shelved changes.
5820
    """
5821
5822
    takes_args = ['file*']
5823
5824
    takes_options = [
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
5825
        'directory',
0.16.74 by Aaron Bentley
Merge with shelf-manager
5826
        'revision',
5827
        Option('all', help='Shelve all changes.'),
5828
        'message',
0.16.108 by Aaron Bentley
Shelf supports multiple diff writers.
5829
        RegistryOption('writer', 'Method to use for writing diffs.',
5830
                       bzrlib.option.diff_writer_registry,
0.16.113 by Aaron Bentley
Change ls-shelf to shelve --list
5831
                       value_switches=True, enum_switch=False),
5832
0.16.119 by Aaron Bentley
Fix option help style.
5833
        Option('list', help='List shelved changes.'),
4100.3.1 by Aaron Bentley
Implement shelve --destroy
5834
        Option('destroy',
5835
               help='Destroy removed changes instead of shelving them.'),
0.16.74 by Aaron Bentley
Merge with shelf-manager
5836
    ]
0.16.117 by Aaron Bentley
Remove references to ls-shelf
5837
    _see_also = ['unshelve']
0.16.74 by Aaron Bentley
Merge with shelf-manager
5838
0.16.108 by Aaron Bentley
Shelf supports multiple diff writers.
5839
    def run(self, revision=None, all=False, file_list=None, message=None,
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
5840
            writer=None, list=False, destroy=False, directory=u'.'):
0.16.113 by Aaron Bentley
Change ls-shelf to shelve --list
5841
        if list:
5842
            return self.run_for_list()
0.16.74 by Aaron Bentley
Merge with shelf-manager
5843
        from bzrlib.shelf_ui import Shelver
0.16.108 by Aaron Bentley
Shelf supports multiple diff writers.
5844
        if writer is None:
5845
            writer = bzrlib.option.diff_writer_registry.get()
0.16.103 by Aaron Bentley
raise UserAbort instead of doing sys.exit
5846
        try:
4603.1.7 by Aaron Bentley
Allow configuring change editor.
5847
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
5848
                file_list, message, destroy=destroy, directory=directory)
4603.1.7 by Aaron Bentley
Allow configuring change editor.
5849
            try:
5850
                shelver.run()
5851
            finally:
4603.1.11 by Aaron Bentley
Implement shelver.finalize
5852
                shelver.finalize()
0.16.103 by Aaron Bentley
raise UserAbort instead of doing sys.exit
5853
        except errors.UserAbort:
5854
            return 0
0.16.74 by Aaron Bentley
Merge with shelf-manager
5855
0.16.113 by Aaron Bentley
Change ls-shelf to shelve --list
5856
    def run_for_list(self):
0.16.118 by Aaron Bentley
Fix open_containing
5857
        tree = WorkingTree.open_containing('.')[0]
5200.3.3 by Robert Collins
Lock methods on ``Tree``, ``Branch`` and ``Repository`` are now
5858
        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.
5859
        manager = tree.get_shelf_manager()
5860
        shelves = manager.active_shelves()
5861
        if len(shelves) == 0:
5862
            note('No shelved changes.')
5863
            return 0
5864
        for shelf_id in reversed(shelves):
5865
            message = manager.get_metadata(shelf_id).get('message')
5866
            if message is None:
5867
                message = '<no message>'
5868
            self.outf.write('%3d: %s\n' % (shelf_id, message))
5869
        return 1
0.16.113 by Aaron Bentley
Change ls-shelf to shelve --list
5870
0.16.74 by Aaron Bentley
Merge with shelf-manager
5871
0.16.80 by Aaron Bentley
Rename shelve2/unshelve2 to shelve/unshelve
5872
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
5873
    __doc__ = """Restore shelved changes.
0.16.74 by Aaron Bentley
Merge with shelf-manager
5874
5875
    By default, the most recently shelved changes are restored. However if you
3990.2.5 by Daniel Watkins
Improve unshelve documentation, as per #327425.
5876
    specify a shelf by id those changes will be restored instead.  This works
5877
    best when the changes don't depend on each other.
0.16.74 by Aaron Bentley
Merge with shelf-manager
5878
    """
5879
5880
    takes_args = ['shelf_id?']
5881
    takes_options = [
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
5882
        'directory',
0.16.74 by Aaron Bentley
Merge with shelf-manager
5883
        RegistryOption.from_kwargs(
5884
            'action', help="The action to perform.",
5885
            enum_switch=False, value_switches=True,
5886
            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
5887
            dry_run="Show changes, but do not apply or remove them.",
5888
            preview="Instead of unshelving the changes, show the diff that "
5889
                    "would result from unshelving.",
4889.1.3 by Martin Pool
New option unshelve --keep
5890
            delete_only="Delete changes without applying them.",
5891
            keep="Apply changes but don't delete them.",
0.16.74 by Aaron Bentley
Merge with shelf-manager
5892
        )
5893
    ]
0.16.117 by Aaron Bentley
Remove references to ls-shelf
5894
    _see_also = ['shelve']
0.16.74 by Aaron Bentley
Merge with shelf-manager
5895
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
5896
    def run(self, shelf_id=None, action='apply', directory=u'.'):
0.16.74 by Aaron Bentley
Merge with shelf-manager
5897
        from bzrlib.shelf_ui import Unshelver
5171.3.13 by Martin von Gagern
Add --directory option to 7 more commands.
5898
        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)
5899
        try:
5900
            unshelver.run()
5901
        finally:
5902
            unshelver.tree.unlock()
0.16.74 by Aaron Bentley
Merge with shelf-manager
5903
5904
4020.1.1 by Jelmer Vernooij
Import clean-tree from bzrtools.
5905
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
5906
    __doc__ = """Remove unwanted files from working tree.
4020.1.1 by Jelmer Vernooij
Import clean-tree from bzrtools.
5907
5908
    By default, only unknown files, not ignored files, are deleted.  Versioned
5909
    files are never deleted.
5910
5911
    Another class is 'detritus', which includes files emitted by bzr during
5912
    normal operations and selftests.  (The value of these files decreases with
5913
    time.)
5914
5915
    If no options are specified, unknown files are deleted.  Otherwise, option
5916
    flags are respected, and may be combined.
5917
5918
    To check what clean-tree will do, use --dry-run.
5919
    """
5171.3.4 by Martin von Gagern
Add --directory option to clean-tree.
5920
    takes_options = ['directory',
5921
                     Option('ignored', help='Delete all ignored files.'),
4020.1.1 by Jelmer Vernooij
Import clean-tree from bzrtools.
5922
                     Option('detritus', help='Delete conflict files, merge'
5923
                            ' backups, and failed selftest dirs.'),
5924
                     Option('unknown',
5925
                            help='Delete files unknown to bzr (default).'),
5926
                     Option('dry-run', help='Show files to delete instead of'
5927
                            ' deleting them.'),
5928
                     Option('force', help='Do not prompt before deleting.')]
5929
    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.
5930
            force=False, directory=u'.'):
4020.1.1 by Jelmer Vernooij
Import clean-tree from bzrtools.
5931
        from bzrlib.clean_tree import clean_tree
5932
        if not (unknown or ignored or detritus):
5933
            unknown = True
5934
        if dry_run:
5935
            force = True
5171.3.4 by Martin von Gagern
Add --directory option to clean-tree.
5936
        clean_tree(directory, unknown=unknown, ignored=ignored,
5937
                   detritus=detritus, dry_run=dry_run, no_prompt=force)
4020.1.1 by Jelmer Vernooij
Import clean-tree from bzrtools.
5938
5939
4273.1.19 by Aaron Bentley
Implement reference command
5940
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
5941
    __doc__ = """list, view and set branch locations for nested trees.
4273.1.19 by Aaron Bentley
Implement reference command
5942
5943
    If no arguments are provided, lists the branch locations for nested trees.
5944
    If one argument is provided, display the branch location for that tree.
5945
    If two arguments are provided, set the branch location for that tree.
5946
    """
5947
5948
    hidden = True
5949
5950
    takes_args = ['path?', 'location?']
5951
5952
    def run(self, path=None, location=None):
5953
        branchdir = '.'
5954
        if path is not None:
5955
            branchdir = path
5956
        tree, branch, relpath =(
5957
            bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
5958
        if path is not None:
5959
            path = relpath
5960
        if tree is None:
5961
            tree = branch.basis_tree()
5962
        if path is None:
5963
            info = branch._get_all_reference_info().iteritems()
5964
            self._display_reference_info(tree, branch, info)
5965
        else:
5966
            file_id = tree.path2id(path)
5967
            if file_id is None:
5968
                raise errors.NotVersionedError(path)
5969
            if location is None:
5970
                info = [(file_id, branch.get_reference_info(file_id))]
5971
                self._display_reference_info(tree, branch, info)
5972
            else:
5973
                branch.set_reference_info(file_id, path, location)
5974
5975
    def _display_reference_info(self, tree, branch, info):
5976
        ref_list = []
5977
        for file_id, (path, location) in info:
5978
            try:
5979
                path = tree.id2path(file_id)
5980
            except errors.NoSuchId:
5981
                pass
5982
            ref_list.append((path, location))
5983
        for path, location in sorted(ref_list):
5984
            self.outf.write('%s %s\n' % (path, location))
5985
5986
5127.1.1 by Martin Pool
version-info is lazily loaded
5987
def _register_lazy_builtins():
5988
    # register lazy builtins from other modules; called at startup and should
5989
    # be only called once.
5990
    for (name, aliases, module_name) in [
5991
        ('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
5127.1.3 by Martin Pool
lazy-load dpush
5992
        ('cmd_dpush', [], 'bzrlib.foreign'),
5127.1.1 by Martin Pool
version-info is lazily loaded
5993
        ('cmd_version_info', [], 'bzrlib.cmd_version_info'),
5127.1.2 by Martin Pool
Lazy-load conflict commands
5994
        ('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
5995
        ('cmd_conflicts', [], 'bzrlib.conflicts'),
5127.1.4 by Martin Pool
Lazy-load sign-my-commits
5996
        ('cmd_sign_my_commits', [], 'bzrlib.sign_my_commits'),
5127.1.1 by Martin Pool
version-info is lazily loaded
5997
        ]:
5998
        builtin_command_registry.register_lazy(name, aliases, module_name)