/brz/remove-bazaar

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