~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Jelmer Vernooij
  • Date: 2011-08-19 22:34:02 UTC
  • mto: This revision was merged to the branch mainline in revision 6089.
  • Revision ID: jelmer@samba.org-20110819223402-wjywqb0fa1xxx522
Use get_transport_from_{url,path} in more places.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005, 2006, 2007 Canonical Ltd
 
1
# Copyright (C) 2005-2011 Canonical Ltd
2
2
#
3
3
# This program is free software; you can redistribute it and/or modify
4
4
# it under the terms of the GNU General Public License as published by
12
12
#
13
13
# You should have received a copy of the GNU General Public License
14
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
 
15
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
16
16
 
17
17
"""builtin bzr commands"""
18
18
 
20
20
 
21
21
from bzrlib.lazy_import import lazy_import
22
22
lazy_import(globals(), """
23
 
import codecs
24
 
import errno
 
23
import cStringIO
25
24
import sys
26
 
import tempfile
 
25
import time
27
26
 
28
27
import bzrlib
29
28
from bzrlib import (
30
 
    branch,
 
29
    bugtracker,
31
30
    bundle,
 
31
    btree_index,
32
32
    bzrdir,
 
33
    directory_service,
33
34
    delta,
34
 
    config,
 
35
    config as _mod_config,
35
36
    errors,
36
 
    ignores,
 
37
    globbing,
 
38
    hooks,
37
39
    log,
38
40
    merge as _mod_merge,
 
41
    merge_directive,
39
42
    osutils,
40
 
    repository,
41
 
    symbol_versioning,
 
43
    reconfigure,
 
44
    rename_map,
 
45
    revision as _mod_revision,
 
46
    static_tuple,
 
47
    timestamp,
42
48
    transport,
43
 
    tree as _mod_tree,
44
49
    ui,
45
50
    urlutils,
 
51
    views,
 
52
    gpg,
46
53
    )
47
54
from bzrlib.branch import Branch
48
 
from bzrlib.bundle.apply_bundle import install_bundle, merge_bundle
49
55
from bzrlib.conflicts import ConflictList
50
 
from bzrlib.revision import common_ancestor
51
 
from bzrlib.revisionspec import RevisionSpec
 
56
from bzrlib.transport import memory
 
57
from bzrlib.revisionspec import RevisionSpec, RevisionInfo
 
58
from bzrlib.smtp_connection import SMTPConnection
52
59
from bzrlib.workingtree import WorkingTree
53
60
""")
54
61
 
55
 
from bzrlib.commands import Command, display_command
56
 
from bzrlib.option import Option, RegistryOption
57
 
from bzrlib.progress import DummyProgress, ProgressPhase
58
 
from bzrlib.trace import mutter, note, log_error, warning, is_quiet, info
59
 
 
60
 
 
61
 
def tree_files(file_list, default_branch=u'.'):
62
 
    try:
63
 
        return internal_tree_files(file_list, default_branch)
64
 
    except errors.FileInWrongBranch, e:
65
 
        raise errors.BzrCommandError("%s is not in the same branch as %s" %
66
 
                                     (e.path, file_list[0]))
 
62
from bzrlib.commands import (
 
63
    Command,
 
64
    builtin_command_registry,
 
65
    display_command,
 
66
    )
 
67
from bzrlib.option import (
 
68
    ListOption,
 
69
    Option,
 
70
    RegistryOption,
 
71
    custom_help,
 
72
    _parse_revision_str,
 
73
    )
 
74
from bzrlib.trace import mutter, note, warning, is_quiet, get_verbosity_level
 
75
from bzrlib import (
 
76
    symbol_versioning,
 
77
    )
 
78
 
 
79
 
 
80
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
 
81
def tree_files(file_list, default_branch=u'.', canonicalize=True,
 
82
    apply_view=True):
 
83
    return internal_tree_files(file_list, default_branch, canonicalize,
 
84
        apply_view)
 
85
 
 
86
 
 
87
def tree_files_for_add(file_list):
 
88
    """
 
89
    Return a tree and list of absolute paths from a file list.
 
90
 
 
91
    Similar to tree_files, but add handles files a bit differently, so it a
 
92
    custom implementation.  In particular, MutableTreeTree.smart_add expects
 
93
    absolute paths, which it immediately converts to relative paths.
 
94
    """
 
95
    # FIXME Would be nice to just return the relative paths like
 
96
    # internal_tree_files does, but there are a large number of unit tests
 
97
    # that assume the current interface to mutabletree.smart_add
 
98
    if file_list:
 
99
        tree, relpath = WorkingTree.open_containing(file_list[0])
 
100
        if tree.supports_views():
 
101
            view_files = tree.views.lookup_view()
 
102
            if view_files:
 
103
                for filename in file_list:
 
104
                    if not osutils.is_inside_any(view_files, filename):
 
105
                        raise errors.FileOutsideView(filename, view_files)
 
106
        file_list = file_list[:]
 
107
        file_list[0] = tree.abspath(relpath)
 
108
    else:
 
109
        tree = WorkingTree.open_containing(u'.')[0]
 
110
        if tree.supports_views():
 
111
            view_files = tree.views.lookup_view()
 
112
            if view_files:
 
113
                file_list = view_files
 
114
                view_str = views.view_display_str(view_files)
 
115
                note("Ignoring files outside view. View is %s" % view_str)
 
116
    return tree, file_list
 
117
 
 
118
 
 
119
def _get_one_revision(command_name, revisions):
 
120
    if revisions is None:
 
121
        return None
 
122
    if len(revisions) != 1:
 
123
        raise errors.BzrCommandError(
 
124
            'bzr %s --revision takes exactly one revision identifier' % (
 
125
                command_name,))
 
126
    return revisions[0]
 
127
 
 
128
 
 
129
def _get_one_revision_tree(command_name, revisions, branch=None, tree=None):
 
130
    """Get a revision tree. Not suitable for commands that change the tree.
 
131
    
 
132
    Specifically, the basis tree in dirstate trees is coupled to the dirstate
 
133
    and doing a commit/uncommit/pull will at best fail due to changing the
 
134
    basis revision data.
 
135
 
 
136
    If tree is passed in, it should be already locked, for lifetime management
 
137
    of the trees internal cached state.
 
138
    """
 
139
    if branch is None:
 
140
        branch = tree.branch
 
141
    if revisions is None:
 
142
        if tree is not None:
 
143
            rev_tree = tree.basis_tree()
 
144
        else:
 
145
            rev_tree = branch.basis_tree()
 
146
    else:
 
147
        revision = _get_one_revision(command_name, revisions)
 
148
        rev_tree = revision.as_tree(branch)
 
149
    return rev_tree
67
150
 
68
151
 
69
152
# XXX: Bad function name; should possibly also be a class method of
70
153
# WorkingTree rather than a function.
71
 
def internal_tree_files(file_list, default_branch=u'.'):
 
154
@symbol_versioning.deprecated_function(symbol_versioning.deprecated_in((2, 3, 0)))
 
155
def internal_tree_files(file_list, default_branch=u'.', canonicalize=True,
 
156
    apply_view=True):
72
157
    """Convert command-line paths to a WorkingTree and relative paths.
73
158
 
 
159
    Deprecated: use WorkingTree.open_containing_paths instead.
 
160
 
74
161
    This is typically used for command-line processors that take one or
75
162
    more filenames, and infer the workingtree that contains them.
76
163
 
77
164
    The filenames given are not required to exist.
78
165
 
79
 
    :param file_list: Filenames to convert.  
 
166
    :param file_list: Filenames to convert.
80
167
 
81
168
    :param default_branch: Fallback tree path to use if file_list is empty or
82
169
        None.
83
170
 
 
171
    :param apply_view: if True and a view is set, apply it or check that
 
172
        specified files are within it
 
173
 
84
174
    :return: workingtree, [relative_paths]
85
175
    """
86
 
    if file_list is None or len(file_list) == 0:
87
 
        return WorkingTree.open_containing(default_branch)[0], file_list
88
 
    tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
89
 
    new_list = []
90
 
    for filename in file_list:
91
 
        try:
92
 
            new_list.append(tree.relpath(osutils.dereference_path(filename)))
93
 
        except errors.PathNotChild:
94
 
            raise errors.FileInWrongBranch(tree.branch, filename)
95
 
    return tree, new_list
96
 
 
97
 
 
98
 
@symbol_versioning.deprecated_function(symbol_versioning.zero_fifteen)
99
 
def get_format_type(typestring):
100
 
    """Parse and return a format specifier."""
101
 
    # Have to use BzrDirMetaFormat1 directly, so that
102
 
    # RepositoryFormat.set_default_format works
103
 
    if typestring == "default":
104
 
        return bzrdir.BzrDirMetaFormat1()
 
176
    return WorkingTree.open_containing_paths(
 
177
        file_list, default_directory='.',
 
178
        canonicalize=True,
 
179
        apply_view=True)
 
180
 
 
181
 
 
182
def _get_view_info_for_change_reporter(tree):
 
183
    """Get the view information from a tree for change reporting."""
 
184
    view_info = None
105
185
    try:
106
 
        return bzrdir.format_registry.make_bzrdir(typestring)
107
 
    except KeyError:
108
 
        msg = 'Unknown bzr format "%s". See "bzr help formats".' % typestring
109
 
        raise errors.BzrCommandError(msg)
 
186
        current_view = tree.views.get_view_info()[0]
 
187
        if current_view is not None:
 
188
            view_info = (current_view, tree.views.lookup_view())
 
189
    except errors.ViewsNotSupported:
 
190
        pass
 
191
    return view_info
 
192
 
 
193
 
 
194
def _open_directory_or_containing_tree_or_branch(filename, directory):
 
195
    """Open the tree or branch containing the specified file, unless
 
196
    the --directory option is used to specify a different branch."""
 
197
    if directory is not None:
 
198
        return (None, Branch.open(directory), filename)
 
199
    return bzrdir.BzrDir.open_containing_tree_or_branch(filename)
110
200
 
111
201
 
112
202
# TODO: Make sure no commands unconditionally use the working directory as a
116
206
# opens the branch?)
117
207
 
118
208
class cmd_status(Command):
119
 
    """Display status summary.
 
209
    __doc__ = """Display status summary.
120
210
 
121
211
    This reports on versioned and unknown files, reporting them
122
212
    grouped by state.  Possible states are:
142
232
    unknown
143
233
        Not versioned and not matching an ignore pattern.
144
234
 
145
 
    To see ignored files use 'bzr ignored'.  For details in the
 
235
    Additionally for directories, symlinks and files with a changed
 
236
    executable bit, Bazaar indicates their type using a trailing
 
237
    character: '/', '@' or '*' respectively. These decorations can be
 
238
    disabled using the '--no-classify' option.
 
239
 
 
240
    To see ignored files use 'bzr ignored'.  For details on the
146
241
    changes to file texts, use 'bzr diff'.
147
 
    
148
 
    --short gives a status flags for each item, similar to the SVN's status
149
 
    command.
150
 
 
151
 
    Column 1: versioning / renames
152
 
      + File versioned
153
 
      - File unversioned
154
 
      R File renamed
155
 
      ? File unknown
156
 
      C File has conflicts
157
 
      P Entry for a pending merge (not a file)
158
 
 
159
 
    Column 2: Contents
160
 
      N File created
161
 
      D File deleted
162
 
      K File kind changed
163
 
      M File modified
164
 
 
165
 
    Column 3: Execute
166
 
      * The execute bit was changed
 
242
 
 
243
    Note that --short or -S gives status flags for each item, similar
 
244
    to Subversion's status command. To get output similar to svn -q,
 
245
    use bzr status -SV.
167
246
 
168
247
    If no arguments are specified, the status of the entire working
169
248
    directory is shown.  Otherwise, only the status of the specified
170
249
    files or directories is reported.  If a directory is given, status
171
250
    is reported for everything inside that directory.
172
251
 
173
 
    If a revision argument is given, the status is calculated against
174
 
    that revision, or between two revisions if two are provided.
 
252
    Before merges are committed, the pending merge tip revisions are
 
253
    shown. To see all pending merge revisions, use the -v option.
 
254
    To skip the display of pending merge information altogether, use
 
255
    the no-pending option or specify a file/directory.
 
256
 
 
257
    To compare the working directory to a specific revision, pass a
 
258
    single revision to the revision argument.
 
259
 
 
260
    To see which files have changed in a specific revision, or between
 
261
    two revisions, pass a revision range to the revision argument.
 
262
    This will produce the same results as calling 'bzr diff --summarize'.
175
263
    """
176
 
    
 
264
 
177
265
    # TODO: --no-recurse, --recurse options
178
 
    
 
266
 
179
267
    takes_args = ['file*']
180
 
    takes_options = ['show-ids', 'revision', 'short']
 
268
    takes_options = ['show-ids', 'revision', 'change', 'verbose',
 
269
                     Option('short', help='Use short status indicators.',
 
270
                            short_name='S'),
 
271
                     Option('versioned', help='Only show versioned files.',
 
272
                            short_name='V'),
 
273
                     Option('no-pending', help='Don\'t show pending merges.',
 
274
                           ),
 
275
                     Option('no-classify',
 
276
                            help='Do not mark object type using indicator.',
 
277
                           ),
 
278
                     ]
181
279
    aliases = ['st', 'stat']
182
280
 
183
281
    encoding_type = 'replace'
184
 
    
 
282
    _see_also = ['diff', 'revert', 'status-flags']
 
283
 
185
284
    @display_command
186
 
    def run(self, show_ids=False, file_list=None, revision=None, short=False):
 
285
    def run(self, show_ids=False, file_list=None, revision=None, short=False,
 
286
            versioned=False, no_pending=False, verbose=False,
 
287
            no_classify=False):
187
288
        from bzrlib.status import show_tree_status
188
289
 
189
 
        tree, file_list = tree_files(file_list)
190
 
            
 
290
        if revision and len(revision) > 2:
 
291
            raise errors.BzrCommandError('bzr status --revision takes exactly'
 
292
                                         ' one or two revision specifiers')
 
293
 
 
294
        tree, relfile_list = WorkingTree.open_containing_paths(file_list)
 
295
        # Avoid asking for specific files when that is not needed.
 
296
        if relfile_list == ['']:
 
297
            relfile_list = None
 
298
            # Don't disable pending merges for full trees other than '.'.
 
299
            if file_list == ['.']:
 
300
                no_pending = True
 
301
        # A specific path within a tree was given.
 
302
        elif relfile_list is not None:
 
303
            no_pending = True
191
304
        show_tree_status(tree, show_ids=show_ids,
192
 
                         specific_files=file_list, revision=revision,
193
 
                         to_file=self.outf,
194
 
                         short=short)
 
305
                         specific_files=relfile_list, revision=revision,
 
306
                         to_file=self.outf, short=short, versioned=versioned,
 
307
                         show_pending=(not no_pending), verbose=verbose,
 
308
                         classify=not no_classify)
195
309
 
196
310
 
197
311
class cmd_cat_revision(Command):
198
 
    """Write out metadata for a revision.
199
 
    
 
312
    __doc__ = """Write out metadata for a revision.
 
313
 
200
314
    The revision to print can either be specified by a specific
201
315
    revision identifier, or you can use --revision.
202
316
    """
203
317
 
204
318
    hidden = True
205
319
    takes_args = ['revision_id?']
206
 
    takes_options = ['revision']
 
320
    takes_options = ['directory', 'revision']
207
321
    # cat-revision is more for frontends so should be exact
208
322
    encoding = 'strict'
209
 
    
 
323
 
 
324
    def print_revision(self, revisions, revid):
 
325
        stream = revisions.get_record_stream([(revid,)], 'unordered', True)
 
326
        record = stream.next()
 
327
        if record.storage_kind == 'absent':
 
328
            raise errors.NoSuchRevision(revisions, revid)
 
329
        revtext = record.get_bytes_as('fulltext')
 
330
        self.outf.write(revtext.decode('utf-8'))
 
331
 
210
332
    @display_command
211
 
    def run(self, revision_id=None, revision=None):
212
 
 
 
333
    def run(self, revision_id=None, revision=None, directory=u'.'):
213
334
        if revision_id is not None and revision is not None:
214
335
            raise errors.BzrCommandError('You can only supply one of'
215
336
                                         ' revision_id or --revision')
216
337
        if revision_id is None and revision is None:
217
338
            raise errors.BzrCommandError('You must supply either'
218
339
                                         ' --revision or a revision_id')
219
 
        b = WorkingTree.open_containing(u'.')[0].branch
220
 
 
221
 
        # TODO: jam 20060112 should cat-revision always output utf-8?
222
 
        if revision_id is not None:
223
 
            self.outf.write(b.repository.get_revision_xml(revision_id).decode('utf-8'))
224
 
        elif revision is not None:
225
 
            for rev in revision:
226
 
                if rev is None:
227
 
                    raise errors.BzrCommandError('You cannot specify a NULL'
228
 
                                                 ' revision.')
229
 
                revno, rev_id = rev.in_history(b)
230
 
                self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
231
 
    
 
340
 
 
341
        b = bzrdir.BzrDir.open_containing_tree_or_branch(directory)[1]
 
342
 
 
343
        revisions = b.repository.revisions
 
344
        if revisions is None:
 
345
            raise errors.BzrCommandError('Repository %r does not support '
 
346
                'access to raw revision texts')
 
347
 
 
348
        b.repository.lock_read()
 
349
        try:
 
350
            # TODO: jam 20060112 should cat-revision always output utf-8?
 
351
            if revision_id is not None:
 
352
                revision_id = osutils.safe_revision_id(revision_id, warn=False)
 
353
                try:
 
354
                    self.print_revision(revisions, revision_id)
 
355
                except errors.NoSuchRevision:
 
356
                    msg = "The repository %s contains no revision %s." % (
 
357
                        b.repository.base, revision_id)
 
358
                    raise errors.BzrCommandError(msg)
 
359
            elif revision is not None:
 
360
                for rev in revision:
 
361
                    if rev is None:
 
362
                        raise errors.BzrCommandError(
 
363
                            'You cannot specify a NULL revision.')
 
364
                    rev_id = rev.as_revision_id(b)
 
365
                    self.print_revision(revisions, rev_id)
 
366
        finally:
 
367
            b.repository.unlock()
 
368
        
 
369
 
 
370
class cmd_dump_btree(Command):
 
371
    __doc__ = """Dump the contents of a btree index file to stdout.
 
372
 
 
373
    PATH is a btree index file, it can be any URL. This includes things like
 
374
    .bzr/repository/pack-names, or .bzr/repository/indices/a34b3a...ca4a4.iix
 
375
 
 
376
    By default, the tuples stored in the index file will be displayed. With
 
377
    --raw, we will uncompress the pages, but otherwise display the raw bytes
 
378
    stored in the index.
 
379
    """
 
380
 
 
381
    # TODO: Do we want to dump the internal nodes as well?
 
382
    # TODO: It would be nice to be able to dump the un-parsed information,
 
383
    #       rather than only going through iter_all_entries. However, this is
 
384
    #       good enough for a start
 
385
    hidden = True
 
386
    encoding_type = 'exact'
 
387
    takes_args = ['path']
 
388
    takes_options = [Option('raw', help='Write the uncompressed bytes out,'
 
389
                                        ' rather than the parsed tuples.'),
 
390
                    ]
 
391
 
 
392
    def run(self, path, raw=False):
 
393
        dirname, basename = osutils.split(path)
 
394
        t = transport.get_transport(dirname)
 
395
        if raw:
 
396
            self._dump_raw_bytes(t, basename)
 
397
        else:
 
398
            self._dump_entries(t, basename)
 
399
 
 
400
    def _get_index_and_bytes(self, trans, basename):
 
401
        """Create a BTreeGraphIndex and raw bytes."""
 
402
        bt = btree_index.BTreeGraphIndex(trans, basename, None)
 
403
        bytes = trans.get_bytes(basename)
 
404
        bt._file = cStringIO.StringIO(bytes)
 
405
        bt._size = len(bytes)
 
406
        return bt, bytes
 
407
 
 
408
    def _dump_raw_bytes(self, trans, basename):
 
409
        import zlib
 
410
 
 
411
        # We need to parse at least the root node.
 
412
        # This is because the first page of every row starts with an
 
413
        # uncompressed header.
 
414
        bt, bytes = self._get_index_and_bytes(trans, basename)
 
415
        for page_idx, page_start in enumerate(xrange(0, len(bytes),
 
416
                                                     btree_index._PAGE_SIZE)):
 
417
            page_end = min(page_start + btree_index._PAGE_SIZE, len(bytes))
 
418
            page_bytes = bytes[page_start:page_end]
 
419
            if page_idx == 0:
 
420
                self.outf.write('Root node:\n')
 
421
                header_end, data = bt._parse_header_from_bytes(page_bytes)
 
422
                self.outf.write(page_bytes[:header_end])
 
423
                page_bytes = data
 
424
            self.outf.write('\nPage %d\n' % (page_idx,))
 
425
            if len(page_bytes) == 0:
 
426
                self.outf.write('(empty)\n');
 
427
            else:
 
428
                decomp_bytes = zlib.decompress(page_bytes)
 
429
                self.outf.write(decomp_bytes)
 
430
                self.outf.write('\n')
 
431
 
 
432
    def _dump_entries(self, trans, basename):
 
433
        try:
 
434
            st = trans.stat(basename)
 
435
        except errors.TransportNotPossible:
 
436
            # We can't stat, so we'll fake it because we have to do the 'get()'
 
437
            # anyway.
 
438
            bt, _ = self._get_index_and_bytes(trans, basename)
 
439
        else:
 
440
            bt = btree_index.BTreeGraphIndex(trans, basename, st.st_size)
 
441
        for node in bt.iter_all_entries():
 
442
            # Node is made up of:
 
443
            # (index, key, value, [references])
 
444
            try:
 
445
                refs = node[3]
 
446
            except IndexError:
 
447
                refs_as_tuples = None
 
448
            else:
 
449
                refs_as_tuples = static_tuple.as_tuples(refs)
 
450
            as_tuple = (tuple(node[1]), node[2], refs_as_tuples)
 
451
            self.outf.write('%s\n' % (as_tuple,))
 
452
 
232
453
 
233
454
class cmd_remove_tree(Command):
234
 
    """Remove the working tree from a given branch/checkout.
 
455
    __doc__ = """Remove the working tree from a given branch/checkout.
235
456
 
236
457
    Since a lightweight checkout is little more than a working tree
237
458
    this will refuse to run against one.
238
 
    """
239
 
 
240
 
    takes_args = ['location?']
241
 
 
242
 
    def run(self, location='.'):
243
 
        d = bzrdir.BzrDir.open(location)
244
 
        
 
459
 
 
460
    To re-create the working tree, use "bzr checkout".
 
461
    """
 
462
    _see_also = ['checkout', 'working-trees']
 
463
    takes_args = ['location*']
 
464
    takes_options = [
 
465
        Option('force',
 
466
               help='Remove the working tree even if it has '
 
467
                    'uncommitted or shelved changes.'),
 
468
        ]
 
469
 
 
470
    def run(self, location_list, force=False):
 
471
        if not location_list:
 
472
            location_list=['.']
 
473
 
 
474
        for location in location_list:
 
475
            d = bzrdir.BzrDir.open(location)
 
476
            
 
477
            try:
 
478
                working = d.open_workingtree()
 
479
            except errors.NoWorkingTree:
 
480
                raise errors.BzrCommandError("No working tree to remove")
 
481
            except errors.NotLocalUrl:
 
482
                raise errors.BzrCommandError("You cannot remove the working tree"
 
483
                                             " of a remote path")
 
484
            if not force:
 
485
                if (working.has_changes()):
 
486
                    raise errors.UncommittedChanges(working)
 
487
                if working.get_shelf_manager().last_shelf() is not None:
 
488
                    raise errors.ShelvedChanges(working)
 
489
 
 
490
            if working.user_url != working.branch.user_url:
 
491
                raise errors.BzrCommandError("You cannot remove the working tree"
 
492
                                             " from a lightweight checkout")
 
493
 
 
494
            d.destroy_workingtree()
 
495
 
 
496
 
 
497
class cmd_repair_workingtree(Command):
 
498
    __doc__ = """Reset the working tree state file.
 
499
 
 
500
    This is not meant to be used normally, but more as a way to recover from
 
501
    filesystem corruption, etc. This rebuilds the working inventory back to a
 
502
    'known good' state. Any new modifications (adding a file, renaming, etc)
 
503
    will be lost, though modified files will still be detected as such.
 
504
 
 
505
    Most users will want something more like "bzr revert" or "bzr update"
 
506
    unless the state file has become corrupted.
 
507
 
 
508
    By default this attempts to recover the current state by looking at the
 
509
    headers of the state file. If the state file is too corrupted to even do
 
510
    that, you can supply --revision to force the state of the tree.
 
511
    """
 
512
 
 
513
    takes_options = ['revision', 'directory',
 
514
        Option('force',
 
515
               help='Reset the tree even if it doesn\'t appear to be'
 
516
                    ' corrupted.'),
 
517
    ]
 
518
    hidden = True
 
519
 
 
520
    def run(self, revision=None, directory='.', force=False):
 
521
        tree, _ = WorkingTree.open_containing(directory)
 
522
        self.add_cleanup(tree.lock_tree_write().unlock)
 
523
        if not force:
 
524
            try:
 
525
                tree.check_state()
 
526
            except errors.BzrError:
 
527
                pass # There seems to be a real error here, so we'll reset
 
528
            else:
 
529
                # Refuse
 
530
                raise errors.BzrCommandError(
 
531
                    'The tree does not appear to be corrupt. You probably'
 
532
                    ' want "bzr revert" instead. Use "--force" if you are'
 
533
                    ' sure you want to reset the working tree.')
 
534
        if revision is None:
 
535
            revision_ids = None
 
536
        else:
 
537
            revision_ids = [r.as_revision_id(tree.branch) for r in revision]
245
538
        try:
246
 
            working = d.open_workingtree()
247
 
        except errors.NoWorkingTree:
248
 
            raise errors.BzrCommandError("No working tree to remove")
249
 
        except errors.NotLocalUrl:
250
 
            raise errors.BzrCommandError("You cannot remove the working tree of a "
251
 
                                         "remote path")
252
 
        
253
 
        working_path = working.bzrdir.root_transport.base
254
 
        branch_path = working.branch.bzrdir.root_transport.base
255
 
        if working_path != branch_path:
256
 
            raise errors.BzrCommandError("You cannot remove the working tree from "
257
 
                                         "a lightweight checkout")
258
 
        
259
 
        d.destroy_workingtree()
260
 
        
 
539
            tree.reset_state(revision_ids)
 
540
        except errors.BzrError, e:
 
541
            if revision_ids is None:
 
542
                extra = (', the header appears corrupt, try passing -r -1'
 
543
                         ' to set the state to the last commit')
 
544
            else:
 
545
                extra = ''
 
546
            raise errors.BzrCommandError('failed to reset the tree state'
 
547
                                         + extra)
 
548
 
261
549
 
262
550
class cmd_revno(Command):
263
 
    """Show current revision number.
 
551
    __doc__ = """Show current revision number.
264
552
 
265
553
    This is equal to the number of revisions on this branch.
266
554
    """
267
555
 
 
556
    _see_also = ['info']
268
557
    takes_args = ['location?']
 
558
    takes_options = [
 
559
        Option('tree', help='Show revno of working tree'),
 
560
        ]
269
561
 
270
562
    @display_command
271
 
    def run(self, location=u'.'):
272
 
        self.outf.write(str(Branch.open_containing(location)[0].revno()))
273
 
        self.outf.write('\n')
 
563
    def run(self, tree=False, location=u'.'):
 
564
        if tree:
 
565
            try:
 
566
                wt = WorkingTree.open_containing(location)[0]
 
567
                self.add_cleanup(wt.lock_read().unlock)
 
568
            except (errors.NoWorkingTree, errors.NotLocalUrl):
 
569
                raise errors.NoWorkingTree(location)
 
570
            revid = wt.last_revision()
 
571
            try:
 
572
                revno_t = wt.branch.revision_id_to_dotted_revno(revid)
 
573
            except errors.NoSuchRevision:
 
574
                revno_t = ('???',)
 
575
            revno = ".".join(str(n) for n in revno_t)
 
576
        else:
 
577
            b = Branch.open_containing(location)[0]
 
578
            self.add_cleanup(b.lock_read().unlock)
 
579
            revno = b.revno()
 
580
        self.cleanup_now()
 
581
        self.outf.write(str(revno) + '\n')
274
582
 
275
583
 
276
584
class cmd_revision_info(Command):
277
 
    """Show revision number and revision id for a given revision identifier.
 
585
    __doc__ = """Show revision number and revision id for a given revision identifier.
278
586
    """
279
587
    hidden = True
280
588
    takes_args = ['revision_info*']
281
 
    takes_options = ['revision']
 
589
    takes_options = [
 
590
        'revision',
 
591
        custom_help('directory',
 
592
            help='Branch to examine, '
 
593
                 'rather than the one containing the working directory.'),
 
594
        Option('tree', help='Show revno of working tree'),
 
595
        ]
282
596
 
283
597
    @display_command
284
 
    def run(self, revision=None, revision_info_list=[]):
 
598
    def run(self, revision=None, directory=u'.', tree=False,
 
599
            revision_info_list=[]):
285
600
 
286
 
        revs = []
 
601
        try:
 
602
            wt = WorkingTree.open_containing(directory)[0]
 
603
            b = wt.branch
 
604
            self.add_cleanup(wt.lock_read().unlock)
 
605
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
606
            wt = None
 
607
            b = Branch.open_containing(directory)[0]
 
608
            self.add_cleanup(b.lock_read().unlock)
 
609
        revision_ids = []
287
610
        if revision is not None:
288
 
            revs.extend(revision)
 
611
            revision_ids.extend(rev.as_revision_id(b) for rev in revision)
289
612
        if revision_info_list is not None:
290
 
            for rev in revision_info_list:
291
 
                revs.append(RevisionSpec.from_string(rev))
292
 
        if len(revs) == 0:
293
 
            raise errors.BzrCommandError('You must supply a revision identifier')
294
 
 
295
 
        b = WorkingTree.open_containing(u'.')[0].branch
296
 
 
297
 
        for rev in revs:
298
 
            revinfo = rev.in_history(b)
299
 
            if revinfo.revno is None:
300
 
                print '     %s' % revinfo.rev_id
 
613
            for rev_str in revision_info_list:
 
614
                rev_spec = RevisionSpec.from_string(rev_str)
 
615
                revision_ids.append(rev_spec.as_revision_id(b))
 
616
        # No arguments supplied, default to the last revision
 
617
        if len(revision_ids) == 0:
 
618
            if tree:
 
619
                if wt is None:
 
620
                    raise errors.NoWorkingTree(directory)
 
621
                revision_ids.append(wt.last_revision())
301
622
            else:
302
 
                print '%4d %s' % (revinfo.revno, revinfo.rev_id)
303
 
 
304
 
    
 
623
                revision_ids.append(b.last_revision())
 
624
 
 
625
        revinfos = []
 
626
        maxlen = 0
 
627
        for revision_id in revision_ids:
 
628
            try:
 
629
                dotted_revno = b.revision_id_to_dotted_revno(revision_id)
 
630
                revno = '.'.join(str(i) for i in dotted_revno)
 
631
            except errors.NoSuchRevision:
 
632
                revno = '???'
 
633
            maxlen = max(maxlen, len(revno))
 
634
            revinfos.append([revno, revision_id])
 
635
 
 
636
        self.cleanup_now()
 
637
        for ri in revinfos:
 
638
            self.outf.write('%*s %s\n' % (maxlen, ri[0], ri[1]))
 
639
 
 
640
 
305
641
class cmd_add(Command):
306
 
    """Add specified files or directories.
 
642
    __doc__ = """Add specified files or directories.
307
643
 
308
644
    In non-recursive mode, all the named items are added, regardless
309
645
    of whether they were previously ignored.  A warning is given if
325
661
    you should never need to explicitly add a directory, they'll just
326
662
    get added when you add a file in the directory.
327
663
 
328
 
    --dry-run will show which files would be added, but not actually 
 
664
    --dry-run will show which files would be added, but not actually
329
665
    add them.
330
666
 
331
667
    --file-ids-from will try to use the file ids from the supplied path.
332
668
    It looks up ids trying to find a matching parent directory with the
333
 
    same filename, and then by pure path.
 
669
    same filename, and then by pure path. This option is rarely needed
 
670
    but can be useful when adding the same logical file into two
 
671
    branches that will be merged later (without showing the two different
 
672
    adds as a conflict). It is also useful when merging another project
 
673
    into a subdirectory of this one.
 
674
    
 
675
    Any files matching patterns in the ignore list will not be added
 
676
    unless they are explicitly mentioned.
334
677
    """
335
678
    takes_args = ['file*']
336
 
    takes_options = ['no-recurse', 'dry-run', 'verbose',
337
 
                     Option('file-ids-from', type=unicode,
338
 
                            help='Lookup file ids from here')]
 
679
    takes_options = [
 
680
        Option('no-recurse',
 
681
               help="Don't recursively add the contents of directories."),
 
682
        Option('dry-run',
 
683
               help="Show what would be done, but don't actually do anything."),
 
684
        'verbose',
 
685
        Option('file-ids-from',
 
686
               type=unicode,
 
687
               help='Lookup file ids from this tree.'),
 
688
        ]
339
689
    encoding_type = 'replace'
 
690
    _see_also = ['remove', 'ignore']
340
691
 
341
692
    def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
342
693
            file_ids_from=None):
343
694
        import bzrlib.add
344
695
 
 
696
        base_tree = None
345
697
        if file_ids_from is not None:
346
698
            try:
347
699
                base_tree, base_path = WorkingTree.open_containing(
357
709
            action = bzrlib.add.AddAction(to_file=self.outf,
358
710
                should_print=(not is_quiet()))
359
711
 
360
 
        added, ignored = bzrlib.add.smart_add(file_list, not no_recurse,
361
 
                                              action=action, save=not dry_run)
 
712
        if base_tree:
 
713
            self.add_cleanup(base_tree.lock_read().unlock)
 
714
        tree, file_list = tree_files_for_add(file_list)
 
715
        added, ignored = tree.smart_add(file_list, not
 
716
            no_recurse, action=action, save=not dry_run)
 
717
        self.cleanup_now()
362
718
        if len(ignored) > 0:
363
719
            if verbose:
364
720
                for glob in sorted(ignored.keys()):
365
721
                    for path in ignored[glob]:
366
 
                        self.outf.write("ignored %s matching \"%s\"\n" 
 
722
                        self.outf.write("ignored %s matching \"%s\"\n"
367
723
                                        % (path, glob))
368
 
            else:
369
 
                match_len = 0
370
 
                for glob, paths in ignored.items():
371
 
                    match_len += len(paths)
372
 
                self.outf.write("ignored %d file(s).\n" % match_len)
373
 
            self.outf.write("If you wish to add some of these files,"
374
 
                            " please add them by name.\n")
375
724
 
376
725
 
377
726
class cmd_mkdir(Command):
378
 
    """Create a new versioned directory.
 
727
    __doc__ = """Create a new versioned directory.
379
728
 
380
729
    This is equivalent to creating the directory and then adding it.
381
730
    """
385
734
 
386
735
    def run(self, dir_list):
387
736
        for d in dir_list:
388
 
            os.mkdir(d)
389
737
            wt, dd = WorkingTree.open_containing(d)
390
 
            wt.add([dd])
391
 
            self.outf.write('added %s\n' % d)
 
738
            base = os.path.dirname(dd)
 
739
            id = wt.path2id(base)
 
740
            if id != None:
 
741
                os.mkdir(d)
 
742
                wt.add([dd])
 
743
                self.outf.write('added %s\n' % d)
 
744
            else:
 
745
                raise errors.NotVersionedError(path=base)
392
746
 
393
747
 
394
748
class cmd_relpath(Command):
395
 
    """Show path of a file relative to root"""
 
749
    __doc__ = """Show path of a file relative to root"""
396
750
 
397
751
    takes_args = ['filename']
398
752
    hidden = True
399
 
    
 
753
 
400
754
    @display_command
401
755
    def run(self, filename):
402
756
        # TODO: jam 20050106 Can relpath return a munged path if
407
761
 
408
762
 
409
763
class cmd_inventory(Command):
410
 
    """Show inventory of the current working copy or a revision.
 
764
    __doc__ = """Show inventory of the current working copy or a revision.
411
765
 
412
766
    It is possible to limit the output to a particular entry
413
767
    type using the --kind option.  For example: --kind file.
414
768
 
415
769
    It is also possible to restrict the list of files to a specific
416
770
    set. For example: bzr inventory --show-ids this/file
417
 
 
418
 
    See also: bzr ls
419
771
    """
420
772
 
421
773
    hidden = True
422
 
 
423
 
    takes_options = ['revision', 'show-ids', 'kind']
424
 
 
 
774
    _see_also = ['ls']
 
775
    takes_options = [
 
776
        'revision',
 
777
        'show-ids',
 
778
        Option('kind',
 
779
               help='List entries of a particular kind: file, directory, symlink.',
 
780
               type=unicode),
 
781
        ]
425
782
    takes_args = ['file*']
426
783
 
427
784
    @display_command
428
785
    def run(self, revision=None, show_ids=False, kind=None, file_list=None):
429
786
        if kind and kind not in ['file', 'directory', 'symlink']:
430
 
            raise errors.BzrCommandError('invalid kind specified')
431
 
 
432
 
        work_tree, file_list = tree_files(file_list)
433
 
 
 
787
            raise errors.BzrCommandError('invalid kind %r specified' % (kind,))
 
788
 
 
789
        revision = _get_one_revision('inventory', revision)
 
790
        work_tree, file_list = WorkingTree.open_containing_paths(file_list)
 
791
        self.add_cleanup(work_tree.lock_read().unlock)
434
792
        if revision is not None:
435
 
            if len(revision) > 1:
436
 
                raise errors.BzrCommandError('bzr inventory --revision takes'
437
 
                                             ' exactly one revision identifier')
438
 
            revision_id = revision[0].in_history(work_tree.branch).rev_id
439
 
            tree = work_tree.branch.repository.revision_tree(revision_id)
440
 
                        
441
 
            # We include work_tree as well as 'tree' here
442
 
            # So that doing '-r 10 path/foo' will lookup whatever file
443
 
            # exists now at 'path/foo' even if it has been renamed, as
444
 
            # well as whatever files existed in revision 10 at path/foo
445
 
            trees = [tree, work_tree]
 
793
            tree = revision.as_tree(work_tree.branch)
 
794
 
 
795
            extra_trees = [work_tree]
 
796
            self.add_cleanup(tree.lock_read().unlock)
446
797
        else:
447
798
            tree = work_tree
448
 
            trees = [tree]
 
799
            extra_trees = []
449
800
 
450
801
        if file_list is not None:
451
 
            file_ids = _mod_tree.find_ids_across_trees(file_list, trees,
452
 
                                                      require_versioned=True)
 
802
            file_ids = tree.paths2ids(file_list, trees=extra_trees,
 
803
                                      require_versioned=True)
453
804
            # find_ids_across_trees may include some paths that don't
454
805
            # exist in 'tree'.
455
 
            entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
456
 
                             for file_id in file_ids if file_id in tree)
 
806
            entries = sorted(
 
807
                (tree.id2path(file_id), tree.inventory[file_id])
 
808
                for file_id in file_ids if tree.has_id(file_id))
457
809
        else:
458
810
            entries = tree.inventory.entries()
459
811
 
 
812
        self.cleanup_now()
460
813
        for path, entry in entries:
461
814
            if kind and kind != entry.kind:
462
815
                continue
468
821
 
469
822
 
470
823
class cmd_mv(Command):
471
 
    """Move or rename a file.
 
824
    __doc__ = """Move or rename a file.
472
825
 
473
 
    usage:
 
826
    :Usage:
474
827
        bzr mv OLDNAME NEWNAME
 
828
 
475
829
        bzr mv SOURCE... DESTINATION
476
830
 
477
831
    If the last argument is a versioned directory, all the other names
488
842
    """
489
843
 
490
844
    takes_args = ['names*']
491
 
    takes_options = [Option("after", help="move only the bzr identifier"
492
 
        " of the file (file has already been moved). Use this flag if"
493
 
        " bzr is not able to detect this itself.")]
 
845
    takes_options = [Option("after", help="Move only the bzr identifier"
 
846
        " of the file, because the file has already been moved."),
 
847
        Option('auto', help='Automatically guess renames.'),
 
848
        Option('dry-run', help='Avoid making changes when guessing renames.'),
 
849
        ]
494
850
    aliases = ['move', 'rename']
495
851
    encoding_type = 'replace'
496
852
 
497
 
    def run(self, names_list, after=False):
 
853
    def run(self, names_list, after=False, auto=False, dry_run=False):
 
854
        if auto:
 
855
            return self.run_auto(names_list, after, dry_run)
 
856
        elif dry_run:
 
857
            raise errors.BzrCommandError('--dry-run requires --auto.')
498
858
        if names_list is None:
499
859
            names_list = []
500
 
 
501
860
        if len(names_list) < 2:
502
861
            raise errors.BzrCommandError("missing file argument")
503
 
        tree, rel_names = tree_files(names_list)
504
 
        
505
 
        if os.path.isdir(names_list[-1]):
 
862
        tree, rel_names = WorkingTree.open_containing_paths(names_list, canonicalize=False)
 
863
        self.add_cleanup(tree.lock_tree_write().unlock)
 
864
        self._run(tree, names_list, rel_names, after)
 
865
 
 
866
    def run_auto(self, names_list, after, dry_run):
 
867
        if names_list is not None and len(names_list) > 1:
 
868
            raise errors.BzrCommandError('Only one path may be specified to'
 
869
                                         ' --auto.')
 
870
        if after:
 
871
            raise errors.BzrCommandError('--after cannot be specified with'
 
872
                                         ' --auto.')
 
873
        work_tree, file_list = WorkingTree.open_containing_paths(
 
874
            names_list, default_directory='.')
 
875
        self.add_cleanup(work_tree.lock_tree_write().unlock)
 
876
        rename_map.RenameMap.guess_renames(work_tree, dry_run)
 
877
 
 
878
    def _run(self, tree, names_list, rel_names, after):
 
879
        into_existing = osutils.isdir(names_list[-1])
 
880
        if into_existing and len(names_list) == 2:
 
881
            # special cases:
 
882
            # a. case-insensitive filesystem and change case of dir
 
883
            # b. move directory after the fact (if the source used to be
 
884
            #    a directory, but now doesn't exist in the working tree
 
885
            #    and the target is an existing directory, just rename it)
 
886
            if (not tree.case_sensitive
 
887
                and rel_names[0].lower() == rel_names[1].lower()):
 
888
                into_existing = False
 
889
            else:
 
890
                inv = tree.inventory
 
891
                # 'fix' the case of a potential 'from'
 
892
                from_id = tree.path2id(
 
893
                            tree.get_canonical_inventory_path(rel_names[0]))
 
894
                if (not osutils.lexists(names_list[0]) and
 
895
                    from_id and inv.get_file_kind(from_id) == "directory"):
 
896
                    into_existing = False
 
897
        # move/rename
 
898
        if into_existing:
506
899
            # move into existing directory
507
 
            for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
508
 
                self.outf.write("%s => %s\n" % pair)
 
900
            # All entries reference existing inventory items, so fix them up
 
901
            # for cicp file-systems.
 
902
            rel_names = tree.get_canonical_inventory_paths(rel_names)
 
903
            for src, dest in tree.move(rel_names[:-1], rel_names[-1], after=after):
 
904
                if not is_quiet():
 
905
                    self.outf.write("%s => %s\n" % (src, dest))
509
906
        else:
510
907
            if len(names_list) != 2:
511
908
                raise errors.BzrCommandError('to mv multiple files the'
512
909
                                             ' destination must be a versioned'
513
910
                                             ' directory')
514
 
            tree.rename_one(rel_names[0], rel_names[1], after=after)
515
 
            self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
516
 
            
517
 
    
 
911
 
 
912
            # for cicp file-systems: the src references an existing inventory
 
913
            # item:
 
914
            src = tree.get_canonical_inventory_path(rel_names[0])
 
915
            # Find the canonical version of the destination:  In all cases, the
 
916
            # parent of the target must be in the inventory, so we fetch the
 
917
            # canonical version from there (we do not always *use* the
 
918
            # canonicalized tail portion - we may be attempting to rename the
 
919
            # case of the tail)
 
920
            canon_dest = tree.get_canonical_inventory_path(rel_names[1])
 
921
            dest_parent = osutils.dirname(canon_dest)
 
922
            spec_tail = osutils.basename(rel_names[1])
 
923
            # For a CICP file-system, we need to avoid creating 2 inventory
 
924
            # entries that differ only by case.  So regardless of the case
 
925
            # we *want* to use (ie, specified by the user or the file-system),
 
926
            # we must always choose to use the case of any existing inventory
 
927
            # items.  The only exception to this is when we are attempting a
 
928
            # case-only rename (ie, canonical versions of src and dest are
 
929
            # the same)
 
930
            dest_id = tree.path2id(canon_dest)
 
931
            if dest_id is None or tree.path2id(src) == dest_id:
 
932
                # No existing item we care about, so work out what case we
 
933
                # are actually going to use.
 
934
                if after:
 
935
                    # If 'after' is specified, the tail must refer to a file on disk.
 
936
                    if dest_parent:
 
937
                        dest_parent_fq = osutils.pathjoin(tree.basedir, dest_parent)
 
938
                    else:
 
939
                        # pathjoin with an empty tail adds a slash, which breaks
 
940
                        # relpath :(
 
941
                        dest_parent_fq = tree.basedir
 
942
 
 
943
                    dest_tail = osutils.canonical_relpath(
 
944
                                    dest_parent_fq,
 
945
                                    osutils.pathjoin(dest_parent_fq, spec_tail))
 
946
                else:
 
947
                    # not 'after', so case as specified is used
 
948
                    dest_tail = spec_tail
 
949
            else:
 
950
                # Use the existing item so 'mv' fails with AlreadyVersioned.
 
951
                dest_tail = os.path.basename(canon_dest)
 
952
            dest = osutils.pathjoin(dest_parent, dest_tail)
 
953
            mutter("attempting to move %s => %s", src, dest)
 
954
            tree.rename_one(src, dest, after=after)
 
955
            if not is_quiet():
 
956
                self.outf.write("%s => %s\n" % (src, dest))
 
957
 
 
958
 
518
959
class cmd_pull(Command):
519
 
    """Turn this branch into a mirror of another branch.
 
960
    __doc__ = """Turn this branch into a mirror of another branch.
520
961
 
521
 
    This command only works on branches that have not diverged.  Branches are
522
 
    considered diverged if the destination branch's most recent commit is one
523
 
    that has not been merged (directly or indirectly) into the parent.
 
962
    By default, this command only works on branches that have not diverged.
 
963
    Branches are considered diverged if the destination branch's most recent 
 
964
    commit is one that has not been merged (directly or indirectly) into the 
 
965
    parent.
524
966
 
525
967
    If branches have diverged, you can use 'bzr merge' to integrate the changes
526
968
    from one into the other.  Once one branch has merged, the other should
527
969
    be able to pull it again.
528
970
 
529
 
    If you want to forget your local changes and just update your branch to
530
 
    match the remote one, use pull --overwrite.
531
 
 
532
 
    If there is no default location set, the first pull will set it.  After
533
 
    that, you can omit the location to use the default.  To change the
534
 
    default, use --remember. The value will only be saved if the remote
535
 
    location can be accessed.
 
971
    If you want to replace your local changes and just want your branch to
 
972
    match the remote one, use pull --overwrite. This will work even if the two
 
973
    branches have diverged.
 
974
 
 
975
    If there is no default location set, the first pull will set it (use
 
976
    --no-remember to avoid settting it). After that, you can omit the
 
977
    location to use the default.  To change the default, use --remember. The
 
978
    value will only be saved if the remote location can be accessed.
 
979
 
 
980
    Note: The location can be specified either in the form of a branch,
 
981
    or in the form of a path to a file containing a merge directive generated
 
982
    with bzr send.
536
983
    """
537
984
 
538
 
    takes_options = ['remember', 'overwrite', 'revision', 'verbose',
539
 
        Option('directory',
540
 
            help='branch to pull into, '
541
 
                 'rather than the one containing the working directory',
542
 
            short_name='d',
543
 
            type=unicode,
 
985
    _see_also = ['push', 'update', 'status-flags', 'send']
 
986
    takes_options = ['remember', 'overwrite', 'revision',
 
987
        custom_help('verbose',
 
988
            help='Show logs of pulled revisions.'),
 
989
        custom_help('directory',
 
990
            help='Branch to pull into, '
 
991
                 'rather than the one containing the working directory.'),
 
992
        Option('local',
 
993
            help="Perform a local pull in a bound "
 
994
                 "branch.  Local pulls are not applied to "
 
995
                 "the master branch."
544
996
            ),
 
997
        Option('show-base',
 
998
            help="Show base revision text in conflicts.")
545
999
        ]
546
1000
    takes_args = ['location?']
547
1001
    encoding_type = 'replace'
548
1002
 
549
 
    def run(self, location=None, remember=False, overwrite=False,
 
1003
    def run(self, location=None, remember=None, overwrite=False,
550
1004
            revision=None, verbose=False,
551
 
            directory=None):
 
1005
            directory=None, local=False,
 
1006
            show_base=False):
552
1007
        # FIXME: too much stuff is in the command class
 
1008
        revision_id = None
 
1009
        mergeable = None
553
1010
        if directory is None:
554
1011
            directory = u'.'
555
1012
        try:
556
1013
            tree_to = WorkingTree.open_containing(directory)[0]
557
1014
            branch_to = tree_to.branch
 
1015
            self.add_cleanup(tree_to.lock_write().unlock)
558
1016
        except errors.NoWorkingTree:
559
1017
            tree_to = None
560
1018
            branch_to = Branch.open_containing(directory)[0]
561
 
 
562
 
        reader = None
 
1019
            self.add_cleanup(branch_to.lock_write().unlock)
 
1020
 
 
1021
        if tree_to is None and show_base:
 
1022
            raise errors.BzrCommandError("Need working tree for --show-base.")
 
1023
 
 
1024
        if local and not branch_to.get_bound_location():
 
1025
            raise errors.LocalRequiresBoundBranch()
 
1026
 
 
1027
        possible_transports = []
563
1028
        if location is not None:
564
1029
            try:
565
 
                reader = bundle.read_bundle_from_url(location)
 
1030
                mergeable = bundle.read_mergeable_from_url(location,
 
1031
                    possible_transports=possible_transports)
566
1032
            except errors.NotABundle:
567
 
                pass # Continue on considering this url a Branch
 
1033
                mergeable = None
568
1034
 
569
1035
        stored_loc = branch_to.get_parent()
570
1036
        if location is None:
574
1040
            else:
575
1041
                display_url = urlutils.unescape_for_display(stored_loc,
576
1042
                        self.outf.encoding)
577
 
                self.outf.write("Using saved location: %s\n" % display_url)
 
1043
                if not is_quiet():
 
1044
                    self.outf.write("Using saved parent location: %s\n" % display_url)
578
1045
                location = stored_loc
579
1046
 
580
 
        if reader is not None:
581
 
            install_bundle(branch_to.repository, reader)
 
1047
        revision = _get_one_revision('pull', revision)
 
1048
        if mergeable is not None:
 
1049
            if revision is not None:
 
1050
                raise errors.BzrCommandError(
 
1051
                    'Cannot use -r with merge directives or bundles')
 
1052
            mergeable.install_revisions(branch_to.repository)
 
1053
            base_revision_id, revision_id, verified = \
 
1054
                mergeable.get_merge_request(branch_to.repository)
582
1055
            branch_from = branch_to
583
1056
        else:
584
 
            branch_from = Branch.open(location)
585
 
 
586
 
            if branch_to.get_parent() is None or remember:
 
1057
            branch_from = Branch.open(location,
 
1058
                possible_transports=possible_transports)
 
1059
            self.add_cleanup(branch_from.lock_read().unlock)
 
1060
            # Remembers if asked explicitly or no previous location is set
 
1061
            if (remember
 
1062
                or (remember is None and branch_to.get_parent() is None)):
587
1063
                branch_to.set_parent(branch_from.base)
588
1064
 
589
 
        rev_id = None
590
 
        if revision is None:
591
 
            if reader is not None:
592
 
                rev_id = reader.target
593
 
        elif len(revision) == 1:
594
 
            rev_id = revision[0].in_history(branch_from).rev_id
595
 
        else:
596
 
            raise errors.BzrCommandError('bzr pull --revision takes one value.')
 
1065
        if revision is not None:
 
1066
            revision_id = revision.as_revision_id(branch_from)
597
1067
 
598
 
        old_rh = branch_to.revision_history()
599
1068
        if tree_to is not None:
600
 
            count = tree_to.pull(branch_from, overwrite, rev_id,
601
 
                delta.ChangeReporter(tree_to.inventory))
 
1069
            view_info = _get_view_info_for_change_reporter(tree_to)
 
1070
            change_reporter = delta._ChangeReporter(
 
1071
                unversioned_filter=tree_to.is_ignored,
 
1072
                view_info=view_info)
 
1073
            result = tree_to.pull(
 
1074
                branch_from, overwrite, revision_id, change_reporter,
 
1075
                possible_transports=possible_transports, local=local,
 
1076
                show_base=show_base)
602
1077
        else:
603
 
            count = branch_to.pull(branch_from, overwrite, rev_id)
604
 
        note('%d revision(s) pulled.' % (count,))
 
1078
            result = branch_to.pull(
 
1079
                branch_from, overwrite, revision_id, local=local)
605
1080
 
606
 
        if verbose:
607
 
            new_rh = branch_to.revision_history()
608
 
            if old_rh != new_rh:
609
 
                # Something changed
610
 
                from bzrlib.log import show_changed_revisions
611
 
                show_changed_revisions(branch_to, old_rh, new_rh,
612
 
                                       to_file=self.outf)
 
1081
        result.report(self.outf)
 
1082
        if verbose and result.old_revid != result.new_revid:
 
1083
            log.show_branch_change(
 
1084
                branch_to, self.outf, result.old_revno,
 
1085
                result.old_revid)
 
1086
        if getattr(result, 'tag_conflicts', None):
 
1087
            return 1
 
1088
        else:
 
1089
            return 0
613
1090
 
614
1091
 
615
1092
class cmd_push(Command):
616
 
    """Update a mirror of this branch.
617
 
    
 
1093
    __doc__ = """Update a mirror of this branch.
 
1094
 
618
1095
    The target branch will not have its working tree populated because this
619
1096
    is both expensive, and is not supported on remote file systems.
620
 
    
 
1097
 
621
1098
    Some smart servers or protocols *may* put the working tree in place in
622
1099
    the future.
623
1100
 
627
1104
 
628
1105
    If branches have diverged, you can use 'bzr push --overwrite' to replace
629
1106
    the other branch completely, discarding its unmerged changes.
630
 
    
 
1107
 
631
1108
    If you want to ensure you have the different changes in the other branch,
632
1109
    do a merge (see bzr help merge) from the other branch, and commit that.
633
1110
    After that you will be able to do a push without '--overwrite'.
634
1111
 
635
 
    If there is no default push location set, the first push will set it.
636
 
    After that, you can omit the location to use the default.  To change the
637
 
    default, use --remember. The value will only be saved if the remote
638
 
    location can be accessed.
 
1112
    If there is no default push location set, the first push will set it (use
 
1113
    --no-remember to avoid settting it).  After that, you can omit the
 
1114
    location to use the default.  To change the default, use --remember. The
 
1115
    value will only be saved if the remote location can be accessed.
639
1116
    """
640
1117
 
641
 
    takes_options = ['remember', 'overwrite', 'verbose',
 
1118
    _see_also = ['pull', 'update', 'working-trees']
 
1119
    takes_options = ['remember', 'overwrite', 'verbose', 'revision',
642
1120
        Option('create-prefix',
643
1121
               help='Create the path leading up to the branch '
644
 
                    'if it does not already exist'),
645
 
        Option('directory',
646
 
            help='branch to push from, '
647
 
                 'rather than the one containing the working directory',
648
 
            short_name='d',
649
 
            type=unicode,
650
 
            ),
 
1122
                    'if it does not already exist.'),
 
1123
        custom_help('directory',
 
1124
            help='Branch to push from, '
 
1125
                 'rather than the one containing the working directory.'),
651
1126
        Option('use-existing-dir',
652
1127
               help='By default push will fail if the target'
653
1128
                    ' directory exists, but does not already'
654
 
                    ' have a control directory. This flag will'
 
1129
                    ' have a control directory.  This flag will'
655
1130
                    ' allow push to proceed.'),
 
1131
        Option('stacked',
 
1132
            help='Create a stacked branch that references the public location '
 
1133
                'of the parent branch.'),
 
1134
        Option('stacked-on',
 
1135
            help='Create a stacked branch that refers to another branch '
 
1136
                'for the commit history. Only the work not present in the '
 
1137
                'referenced branch is included in the branch created.',
 
1138
            type=unicode),
 
1139
        Option('strict',
 
1140
               help='Refuse to push if there are uncommitted changes in'
 
1141
               ' the working tree, --no-strict disables the check.'),
 
1142
        Option('no-tree',
 
1143
               help="Don't populate the working tree, even for protocols"
 
1144
               " that support it."),
656
1145
        ]
657
1146
    takes_args = ['location?']
658
1147
    encoding_type = 'replace'
659
1148
 
660
 
    def run(self, location=None, remember=False, overwrite=False,
661
 
            create_prefix=False, verbose=False,
662
 
            use_existing_dir=False,
663
 
            directory=None):
664
 
        # FIXME: Way too big!  Put this into a function called from the
665
 
        # command.
 
1149
    def run(self, location=None, remember=None, overwrite=False,
 
1150
        create_prefix=False, verbose=False, revision=None,
 
1151
        use_existing_dir=False, directory=None, stacked_on=None,
 
1152
        stacked=False, strict=None, no_tree=False):
 
1153
        from bzrlib.push import _show_push_branch
 
1154
 
666
1155
        if directory is None:
667
1156
            directory = '.'
668
 
        br_from = Branch.open_containing(directory)[0]
669
 
        stored_loc = br_from.get_push_location()
 
1157
        # Get the source branch
 
1158
        (tree, br_from,
 
1159
         _unused) = bzrdir.BzrDir.open_containing_tree_or_branch(directory)
 
1160
        # Get the tip's revision_id
 
1161
        revision = _get_one_revision('push', revision)
 
1162
        if revision is not None:
 
1163
            revision_id = revision.in_history(br_from).rev_id
 
1164
        else:
 
1165
            revision_id = None
 
1166
        if tree is not None and revision_id is None:
 
1167
            tree.check_changed_or_out_of_date(
 
1168
                strict, 'push_strict',
 
1169
                more_error='Use --no-strict to force the push.',
 
1170
                more_warning='Uncommitted changes will not be pushed.')
 
1171
        # Get the stacked_on branch, if any
 
1172
        if stacked_on is not None:
 
1173
            stacked_on = urlutils.normalize_url(stacked_on)
 
1174
        elif stacked:
 
1175
            parent_url = br_from.get_parent()
 
1176
            if parent_url:
 
1177
                parent = Branch.open(parent_url)
 
1178
                stacked_on = parent.get_public_branch()
 
1179
                if not stacked_on:
 
1180
                    # I considered excluding non-http url's here, thus forcing
 
1181
                    # 'public' branches only, but that only works for some
 
1182
                    # users, so it's best to just depend on the user spotting an
 
1183
                    # error by the feedback given to them. RBC 20080227.
 
1184
                    stacked_on = parent_url
 
1185
            if not stacked_on:
 
1186
                raise errors.BzrCommandError(
 
1187
                    "Could not determine branch to refer to.")
 
1188
 
 
1189
        # Get the destination location
670
1190
        if location is None:
 
1191
            stored_loc = br_from.get_push_location()
671
1192
            if stored_loc is None:
672
 
                raise errors.BzrCommandError("No push location known or specified.")
 
1193
                raise errors.BzrCommandError(
 
1194
                    "No push location known or specified.")
673
1195
            else:
674
1196
                display_url = urlutils.unescape_for_display(stored_loc,
675
1197
                        self.outf.encoding)
676
 
                self.outf.write("Using saved location: %s\n" % display_url)
 
1198
                note("Using saved push location: %s" % display_url)
677
1199
                location = stored_loc
678
1200
 
679
 
        to_transport = transport.get_transport(location)
680
 
        location_url = to_transport.base
681
 
 
682
 
        old_rh = []
683
 
        count = 0
684
 
 
685
 
        br_to = repository_to = dir_to = None
686
 
        try:
687
 
            dir_to = bzrdir.BzrDir.open_from_transport(to_transport)
688
 
        except errors.NotBranchError:
689
 
            pass # Didn't find anything
690
 
        else:
691
 
            # If we can open a branch, use its direct repository, otherwise see
692
 
            # if there is a repository without a branch.
693
 
            try:
694
 
                br_to = dir_to.open_branch()
695
 
            except errors.NotBranchError:
696
 
                # Didn't find a branch, can we find a repository?
697
 
                try:
698
 
                    repository_to = dir_to.find_repository()
699
 
                except errors.NoRepositoryPresent:
700
 
                    pass
701
 
            else:
702
 
                # Found a branch, so we must have found a repository
703
 
                repository_to = br_to.repository
704
 
 
705
 
        old_rh = []
706
 
        if dir_to is None:
707
 
            # XXX: Refactor the create_prefix/no_create_prefix code into a
708
 
            #      common helper function
709
 
            try:
710
 
                to_transport.mkdir('.')
711
 
            except errors.FileExists:
712
 
                if not use_existing_dir:
713
 
                    raise errors.BzrCommandError("Target directory %s"
714
 
                         " already exists, but does not have a valid .bzr"
715
 
                         " directory. Supply --use-existing-dir to push"
716
 
                         " there anyway." % location)
717
 
            except errors.NoSuchFile:
718
 
                if not create_prefix:
719
 
                    raise errors.BzrCommandError("Parent directory of %s"
720
 
                        " does not exist."
721
 
                        "\nYou may supply --create-prefix to create all"
722
 
                        " leading parent directories."
723
 
                        % location)
724
 
 
725
 
                cur_transport = to_transport
726
 
                needed = [cur_transport]
727
 
                # Recurse upwards until we can create a directory successfully
728
 
                while True:
729
 
                    new_transport = cur_transport.clone('..')
730
 
                    if new_transport.base == cur_transport.base:
731
 
                        raise errors.BzrCommandError("Failed to create path"
732
 
                                                     " prefix for %s."
733
 
                                                     % location)
734
 
                    try:
735
 
                        new_transport.mkdir('.')
736
 
                    except errors.NoSuchFile:
737
 
                        needed.append(new_transport)
738
 
                        cur_transport = new_transport
739
 
                    else:
740
 
                        break
741
 
 
742
 
                # Now we only need to create child directories
743
 
                while needed:
744
 
                    cur_transport = needed.pop()
745
 
                    cur_transport.mkdir('.')
746
 
            
747
 
            # Now the target directory exists, but doesn't have a .bzr
748
 
            # directory. So we need to create it, along with any work to create
749
 
            # all of the dependent branches, etc.
750
 
            dir_to = br_from.bzrdir.clone(location_url,
751
 
                revision_id=br_from.last_revision())
752
 
            br_to = dir_to.open_branch()
753
 
            count = br_to.last_revision_info()[0]
754
 
            # We successfully created the target, remember it
755
 
            if br_from.get_push_location() is None or remember:
756
 
                br_from.set_push_location(br_to.base)
757
 
        elif repository_to is None:
758
 
            # we have a bzrdir but no branch or repository
759
 
            # XXX: Figure out what to do other than complain.
760
 
            raise errors.BzrCommandError("At %s you have a valid .bzr control"
761
 
                " directory, but not a branch or repository. This is an"
762
 
                " unsupported configuration. Please move the target directory"
763
 
                " out of the way and try again."
764
 
                % location)
765
 
        elif br_to is None:
766
 
            # We have a repository but no branch, copy the revisions, and then
767
 
            # create a branch.
768
 
            last_revision_id = br_from.last_revision()
769
 
            repository_to.fetch(br_from.repository,
770
 
                                revision_id=last_revision_id)
771
 
            br_to = br_from.clone(dir_to, revision_id=last_revision_id)
772
 
            count = len(br_to.revision_history())
773
 
            if br_from.get_push_location() is None or remember:
774
 
                br_from.set_push_location(br_to.base)
775
 
        else: # We have a valid to branch
776
 
            # We were able to connect to the remote location, so remember it
777
 
            # we don't need to successfully push because of possible divergence.
778
 
            if br_from.get_push_location() is None or remember:
779
 
                br_from.set_push_location(br_to.base)
780
 
            old_rh = br_to.revision_history()
781
 
            try:
782
 
                try:
783
 
                    tree_to = dir_to.open_workingtree()
784
 
                except errors.NotLocalUrl:
785
 
                    warning('This transport does not update the working '
786
 
                            'tree of: %s' % (br_to.base,))
787
 
                    count = br_from.push(br_to, overwrite)
788
 
                except errors.NoWorkingTree:
789
 
                    count = br_from.push(br_to, overwrite)
790
 
                else:
791
 
                    tree_to.lock_write()
792
 
                    try:
793
 
                        count = br_from.push(tree_to.branch, overwrite)
794
 
                        tree_to.update()
795
 
                    finally:
796
 
                        tree_to.unlock()
797
 
            except errors.DivergedBranches:
798
 
                raise errors.BzrCommandError('These branches have diverged.'
799
 
                                        '  Try using "merge" and then "push".')
800
 
        note('%d revision(s) pushed.' % (count,))
801
 
 
802
 
        if verbose:
803
 
            new_rh = br_to.revision_history()
804
 
            if old_rh != new_rh:
805
 
                # Something changed
806
 
                from bzrlib.log import show_changed_revisions
807
 
                show_changed_revisions(br_to, old_rh, new_rh,
808
 
                                       to_file=self.outf)
 
1201
        _show_push_branch(br_from, revision_id, location, self.outf,
 
1202
            verbose=verbose, overwrite=overwrite, remember=remember,
 
1203
            stacked_on=stacked_on, create_prefix=create_prefix,
 
1204
            use_existing_dir=use_existing_dir, no_tree=no_tree)
809
1205
 
810
1206
 
811
1207
class cmd_branch(Command):
812
 
    """Create a new copy of a branch.
 
1208
    __doc__ = """Create a new branch that is a copy of an existing branch.
813
1209
 
814
1210
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
815
1211
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
 
1212
    If the FROM_LOCATION has no / or path separator embedded, the TO_LOCATION
 
1213
    is derived from the FROM_LOCATION by stripping a leading scheme or drive
 
1214
    identifier, if any. For example, "branch lp:foo-bar" will attempt to
 
1215
    create ./foo-bar.
816
1216
 
817
1217
    To retrieve the branch as of a particular revision, supply the --revision
818
1218
    parameter, as in "branch foo/bar -r 5".
819
1219
 
820
 
    --basis is to speed up branching from remote branches.  When specified, it
821
 
    copies all the file-contents, inventory and revision data from the basis
822
 
    branch before copying anything from the remote branch.
 
1220
    The synonyms 'clone' and 'get' for this command are deprecated.
823
1221
    """
 
1222
 
 
1223
    _see_also = ['checkout']
824
1224
    takes_args = ['from_location', 'to_location?']
825
 
    takes_options = ['revision', 'basis']
 
1225
    takes_options = ['revision',
 
1226
        Option('hardlink', help='Hard-link working tree files where possible.'),
 
1227
        Option('files-from', type=str,
 
1228
               help="Get file contents from this tree."),
 
1229
        Option('no-tree',
 
1230
            help="Create a branch without a working-tree."),
 
1231
        Option('switch',
 
1232
            help="Switch the checkout in the current directory "
 
1233
                 "to the new branch."),
 
1234
        Option('stacked',
 
1235
            help='Create a stacked branch referring to the source branch. '
 
1236
                'The new branch will depend on the availability of the source '
 
1237
                'branch for all operations.'),
 
1238
        Option('standalone',
 
1239
               help='Do not use a shared repository, even if available.'),
 
1240
        Option('use-existing-dir',
 
1241
               help='By default branch will fail if the target'
 
1242
                    ' directory exists, but does not already'
 
1243
                    ' have a control directory.  This flag will'
 
1244
                    ' allow branch to proceed.'),
 
1245
        Option('bind',
 
1246
            help="Bind new branch to from location."),
 
1247
        ]
826
1248
    aliases = ['get', 'clone']
827
1249
 
828
 
    def run(self, from_location, to_location=None, revision=None, basis=None):
829
 
        if revision is None:
830
 
            revision = [None]
831
 
        elif len(revision) > 1:
832
 
            raise errors.BzrCommandError(
833
 
                'bzr branch --revision takes exactly 1 revision value')
834
 
 
835
 
        br_from = Branch.open(from_location)
836
 
        br_from.lock_read()
837
 
        try:
838
 
            if basis is not None:
839
 
                basis_dir = bzrdir.BzrDir.open_containing(basis)[0]
840
 
            else:
841
 
                basis_dir = None
842
 
            if len(revision) == 1 and revision[0] is not None:
843
 
                revision_id = revision[0].in_history(br_from)[1]
844
 
            else:
845
 
                # FIXME - wt.last_revision, fallback to branch, fall back to
846
 
                # None or perhaps NULL_REVISION to mean copy nothing
847
 
                # RBC 20060209
848
 
                revision_id = br_from.last_revision()
849
 
            if to_location is None:
850
 
                to_location = os.path.basename(from_location.rstrip("/\\"))
851
 
                name = None
852
 
            else:
853
 
                name = os.path.basename(to_location) + '\n'
854
 
 
855
 
            to_transport = transport.get_transport(to_location)
856
 
            try:
857
 
                to_transport.mkdir('.')
858
 
            except errors.FileExists:
859
 
                raise errors.BzrCommandError('Target directory "%s" already'
860
 
                                             ' exists.' % to_location)
861
 
            except errors.NoSuchFile:
862
 
                raise errors.BzrCommandError('Parent of "%s" does not exist.'
863
 
                                             % to_location)
864
 
            try:
865
 
                # preserve whatever source format we have.
866
 
                dir = br_from.bzrdir.sprout(to_transport.base,
867
 
                        revision_id, basis_dir)
868
 
                branch = dir.open_branch()
869
 
            except errors.NoSuchRevision:
870
 
                to_transport.delete_tree('.')
871
 
                msg = "The branch %s has no revision %s." % (from_location, revision[0])
872
 
                raise errors.BzrCommandError(msg)
873
 
            except errors.UnlistableBranch:
874
 
                osutils.rmtree(to_location)
875
 
                msg = "The branch %s cannot be used as a --basis" % (basis,)
876
 
                raise errors.BzrCommandError(msg)
877
 
            if name:
878
 
                branch.control_files.put_utf8('branch-name', name)
 
1250
    def run(self, from_location, to_location=None, revision=None,
 
1251
            hardlink=False, stacked=False, standalone=False, no_tree=False,
 
1252
            use_existing_dir=False, switch=False, bind=False,
 
1253
            files_from=None):
 
1254
        from bzrlib import switch as _mod_switch
 
1255
        from bzrlib.tag import _merge_tags_if_possible
 
1256
        if self.invoked_as in ['get', 'clone']:
 
1257
            ui.ui_factory.show_user_warning(
 
1258
                'deprecated_command',
 
1259
                deprecated_name=self.invoked_as,
 
1260
                recommended_name='branch',
 
1261
                deprecated_in_version='2.4')
 
1262
        accelerator_tree, br_from = bzrdir.BzrDir.open_tree_or_branch(
 
1263
            from_location)
 
1264
        if not (hardlink or files_from):
 
1265
            # accelerator_tree is usually slower because you have to read N
 
1266
            # files (no readahead, lots of seeks, etc), but allow the user to
 
1267
            # explicitly request it
 
1268
            accelerator_tree = None
 
1269
        if files_from is not None and files_from != from_location:
 
1270
            accelerator_tree = WorkingTree.open(files_from)
 
1271
        revision = _get_one_revision('branch', revision)
 
1272
        self.add_cleanup(br_from.lock_read().unlock)
 
1273
        if revision is not None:
 
1274
            revision_id = revision.as_revision_id(br_from)
 
1275
        else:
 
1276
            # FIXME - wt.last_revision, fallback to branch, fall back to
 
1277
            # None or perhaps NULL_REVISION to mean copy nothing
 
1278
            # RBC 20060209
 
1279
            revision_id = br_from.last_revision()
 
1280
        if to_location is None:
 
1281
            to_location = urlutils.derive_to_location(from_location)
 
1282
        to_transport = transport.get_transport(to_location)
 
1283
        try:
 
1284
            to_transport.mkdir('.')
 
1285
        except errors.FileExists:
 
1286
            if not use_existing_dir:
 
1287
                raise errors.BzrCommandError('Target directory "%s" '
 
1288
                    'already exists.' % to_location)
 
1289
            else:
 
1290
                try:
 
1291
                    bzrdir.BzrDir.open_from_transport(to_transport)
 
1292
                except errors.NotBranchError:
 
1293
                    pass
 
1294
                else:
 
1295
                    raise errors.AlreadyBranchError(to_location)
 
1296
        except errors.NoSuchFile:
 
1297
            raise errors.BzrCommandError('Parent of "%s" does not exist.'
 
1298
                                         % to_location)
 
1299
        try:
 
1300
            # preserve whatever source format we have.
 
1301
            dir = br_from.bzrdir.sprout(to_transport.base, revision_id,
 
1302
                                        possible_transports=[to_transport],
 
1303
                                        accelerator_tree=accelerator_tree,
 
1304
                                        hardlink=hardlink, stacked=stacked,
 
1305
                                        force_new_repo=standalone,
 
1306
                                        create_tree_if_local=not no_tree,
 
1307
                                        source_branch=br_from)
 
1308
            branch = dir.open_branch()
 
1309
        except errors.NoSuchRevision:
 
1310
            to_transport.delete_tree('.')
 
1311
            msg = "The branch %s has no revision %s." % (from_location,
 
1312
                revision)
 
1313
            raise errors.BzrCommandError(msg)
 
1314
        _merge_tags_if_possible(br_from, branch)
 
1315
        # If the source branch is stacked, the new branch may
 
1316
        # be stacked whether we asked for that explicitly or not.
 
1317
        # We therefore need a try/except here and not just 'if stacked:'
 
1318
        try:
 
1319
            note('Created new stacked branch referring to %s.' %
 
1320
                branch.get_stacked_on_url())
 
1321
        except (errors.NotStacked, errors.UnstackableBranchFormat,
 
1322
            errors.UnstackableRepositoryFormat), e:
879
1323
            note('Branched %d revision(s).' % branch.revno())
880
 
        finally:
881
 
            br_from.unlock()
 
1324
        if bind:
 
1325
            # Bind to the parent
 
1326
            parent_branch = Branch.open(from_location)
 
1327
            branch.bind(parent_branch)
 
1328
            note('New branch bound to %s' % from_location)
 
1329
        if switch:
 
1330
            # Switch to the new branch
 
1331
            wt, _ = WorkingTree.open_containing('.')
 
1332
            _mod_switch.switch(wt.bzrdir, branch)
 
1333
            note('Switched to branch: %s',
 
1334
                urlutils.unescape_for_display(branch.base, 'utf-8'))
 
1335
 
 
1336
 
 
1337
class cmd_branches(Command):
 
1338
    __doc__ = """List the branches available at the current location.
 
1339
 
 
1340
    This command will print the names of all the branches at the current location.
 
1341
    """
 
1342
 
 
1343
    takes_args = ['location?']
 
1344
 
 
1345
    def run(self, location="."):
 
1346
        dir = bzrdir.BzrDir.open_containing(location)[0]
 
1347
        for branch in dir.list_branches():
 
1348
            if branch.name is None:
 
1349
                self.outf.write(" (default)\n")
 
1350
            else:
 
1351
                self.outf.write(" %s\n" % branch.name.encode(self.outf.encoding))
882
1352
 
883
1353
 
884
1354
class cmd_checkout(Command):
885
 
    """Create a new checkout of an existing branch.
 
1355
    __doc__ = """Create a new checkout of an existing branch.
886
1356
 
887
1357
    If BRANCH_LOCATION is omitted, checkout will reconstitute a working tree for
888
1358
    the branch found in '.'. This is useful if you have removed the working tree
889
1359
    or if it was never created - i.e. if you pushed the branch to its current
890
1360
    location using SFTP.
891
 
    
 
1361
 
892
1362
    If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
893
1363
    be used.  In other words, "checkout ../foo/bar" will attempt to create ./bar.
 
1364
    If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
 
1365
    is derived from the BRANCH_LOCATION by stripping a leading scheme or drive
 
1366
    identifier, if any. For example, "checkout lp:foo-bar" will attempt to
 
1367
    create ./foo-bar.
894
1368
 
895
1369
    To retrieve the branch as of a particular revision, supply the --revision
896
1370
    parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
897
1371
    out of date [so you cannot commit] but it may be useful (i.e. to examine old
898
1372
    code.)
899
 
 
900
 
    --basis is to speed up checking out from remote branches.  When specified, it
901
 
    uses the inventory and file contents from the basis branch in preference to the
902
 
    branch being checked out.
903
 
 
904
 
    See "help checkouts" for more information on checkouts.
905
1373
    """
 
1374
 
 
1375
    _see_also = ['checkouts', 'branch']
906
1376
    takes_args = ['branch_location?', 'to_location?']
907
 
    takes_options = ['revision', # , 'basis']
 
1377
    takes_options = ['revision',
908
1378
                     Option('lightweight',
909
 
                            help="perform a lightweight checkout. Lightweight "
 
1379
                            help="Perform a lightweight checkout.  Lightweight "
910
1380
                                 "checkouts depend on access to the branch for "
911
 
                                 "every operation. Normal checkouts can perform "
 
1381
                                 "every operation.  Normal checkouts can perform "
912
1382
                                 "common operations like diff and status without "
913
1383
                                 "such access, and also support local commits."
914
1384
                            ),
 
1385
                     Option('files-from', type=str,
 
1386
                            help="Get file contents from this tree."),
 
1387
                     Option('hardlink',
 
1388
                            help='Hard-link working tree files where possible.'
 
1389
                            ),
915
1390
                     ]
916
1391
    aliases = ['co']
917
1392
 
918
 
    def run(self, branch_location=None, to_location=None, revision=None, basis=None,
919
 
            lightweight=False):
920
 
        if revision is None:
921
 
            revision = [None]
922
 
        elif len(revision) > 1:
923
 
            raise errors.BzrCommandError(
924
 
                'bzr checkout --revision takes exactly 1 revision value')
 
1393
    def run(self, branch_location=None, to_location=None, revision=None,
 
1394
            lightweight=False, files_from=None, hardlink=False):
925
1395
        if branch_location is None:
926
1396
            branch_location = osutils.getcwd()
927
1397
            to_location = branch_location
928
 
        source = Branch.open(branch_location)
929
 
        if len(revision) == 1 and revision[0] is not None:
930
 
            revision_id = revision[0].in_history(source)[1]
 
1398
        accelerator_tree, source = bzrdir.BzrDir.open_tree_or_branch(
 
1399
            branch_location)
 
1400
        if not (hardlink or files_from):
 
1401
            # accelerator_tree is usually slower because you have to read N
 
1402
            # files (no readahead, lots of seeks, etc), but allow the user to
 
1403
            # explicitly request it
 
1404
            accelerator_tree = None
 
1405
        revision = _get_one_revision('checkout', revision)
 
1406
        if files_from is not None and files_from != branch_location:
 
1407
            accelerator_tree = WorkingTree.open(files_from)
 
1408
        if revision is not None:
 
1409
            revision_id = revision.as_revision_id(source)
931
1410
        else:
932
1411
            revision_id = None
933
1412
        if to_location is None:
934
 
            to_location = os.path.basename(branch_location.rstrip("/\\"))
935
 
        # if the source and to_location are the same, 
 
1413
            to_location = urlutils.derive_to_location(branch_location)
 
1414
        # if the source and to_location are the same,
936
1415
        # and there is no working tree,
937
1416
        # then reconstitute a branch
938
1417
        if (osutils.abspath(to_location) ==
940
1419
            try:
941
1420
                source.bzrdir.open_workingtree()
942
1421
            except errors.NoWorkingTree:
943
 
                source.bzrdir.create_workingtree()
 
1422
                source.bzrdir.create_workingtree(revision_id)
944
1423
                return
945
 
        try:
946
 
            os.mkdir(to_location)
947
 
        except OSError, e:
948
 
            if e.errno == errno.EEXIST:
949
 
                raise errors.BzrCommandError('Target directory "%s" already'
950
 
                                             ' exists.' % to_location)
951
 
            if e.errno == errno.ENOENT:
952
 
                raise errors.BzrCommandError('Parent of "%s" does not exist.'
953
 
                                             % to_location)
954
 
            else:
955
 
                raise
956
 
        source.create_checkout(to_location, revision_id, lightweight)
 
1424
        source.create_checkout(to_location, revision_id, lightweight,
 
1425
                               accelerator_tree, hardlink)
957
1426
 
958
1427
 
959
1428
class cmd_renames(Command):
960
 
    """Show list of renamed files.
 
1429
    __doc__ = """Show list of renamed files.
961
1430
    """
962
1431
    # TODO: Option to show renames between two historical versions.
963
1432
 
964
1433
    # TODO: Only show renames under dir, rather than in the whole branch.
 
1434
    _see_also = ['status']
965
1435
    takes_args = ['dir?']
966
1436
 
967
1437
    @display_command
968
1438
    def run(self, dir=u'.'):
969
1439
        tree = WorkingTree.open_containing(dir)[0]
970
 
        old_inv = tree.basis_tree().inventory
971
 
        new_inv = tree.read_working_inventory()
972
 
        renames = list(_mod_tree.find_renames(old_inv, new_inv))
 
1440
        self.add_cleanup(tree.lock_read().unlock)
 
1441
        new_inv = tree.inventory
 
1442
        old_tree = tree.basis_tree()
 
1443
        self.add_cleanup(old_tree.lock_read().unlock)
 
1444
        old_inv = old_tree.inventory
 
1445
        renames = []
 
1446
        iterator = tree.iter_changes(old_tree, include_unchanged=True)
 
1447
        for f, paths, c, v, p, n, k, e in iterator:
 
1448
            if paths[0] == paths[1]:
 
1449
                continue
 
1450
            if None in (paths):
 
1451
                continue
 
1452
            renames.append(paths)
973
1453
        renames.sort()
974
1454
        for old_name, new_name in renames:
975
1455
            self.outf.write("%s => %s\n" % (old_name, new_name))
976
1456
 
977
1457
 
978
1458
class cmd_update(Command):
979
 
    """Update a tree to have the latest code committed to its branch.
980
 
    
 
1459
    __doc__ = """Update a tree to have the latest code committed to its branch.
 
1460
 
981
1461
    This will perform a merge into the working tree, and may generate
982
 
    conflicts. If you have any local changes, you will still 
 
1462
    conflicts. If you have any local changes, you will still
983
1463
    need to commit them after the update for the update to be complete.
984
 
    
985
 
    If you want to discard your local changes, you can just do a 
 
1464
 
 
1465
    If you want to discard your local changes, you can just do a
986
1466
    'bzr revert' instead of 'bzr commit' after the update.
 
1467
 
 
1468
    If you want to restore a file that has been removed locally, use
 
1469
    'bzr revert' instead of 'bzr update'.
 
1470
 
 
1471
    If the tree's branch is bound to a master branch, it will also update
 
1472
    the branch from the master.
987
1473
    """
 
1474
 
 
1475
    _see_also = ['pull', 'working-trees', 'status-flags']
988
1476
    takes_args = ['dir?']
 
1477
    takes_options = ['revision',
 
1478
                     Option('show-base',
 
1479
                            help="Show base revision text in conflicts."),
 
1480
                     ]
989
1481
    aliases = ['up']
990
1482
 
991
 
    def run(self, dir='.'):
 
1483
    def run(self, dir='.', revision=None, show_base=None):
 
1484
        if revision is not None and len(revision) != 1:
 
1485
            raise errors.BzrCommandError(
 
1486
                        "bzr update --revision takes exactly one revision")
992
1487
        tree = WorkingTree.open_containing(dir)[0]
993
 
        master = tree.branch.get_master_branch()
 
1488
        branch = tree.branch
 
1489
        possible_transports = []
 
1490
        master = branch.get_master_branch(
 
1491
            possible_transports=possible_transports)
994
1492
        if master is not None:
 
1493
            branch_location = master.base
995
1494
            tree.lock_write()
996
1495
        else:
 
1496
            branch_location = tree.branch.base
997
1497
            tree.lock_tree_write()
 
1498
        self.add_cleanup(tree.unlock)
 
1499
        # get rid of the final '/' and be ready for display
 
1500
        branch_location = urlutils.unescape_for_display(
 
1501
            branch_location.rstrip('/'),
 
1502
            self.outf.encoding)
 
1503
        existing_pending_merges = tree.get_parent_ids()[1:]
 
1504
        if master is None:
 
1505
            old_tip = None
 
1506
        else:
 
1507
            # may need to fetch data into a heavyweight checkout
 
1508
            # XXX: this may take some time, maybe we should display a
 
1509
            # message
 
1510
            old_tip = branch.update(possible_transports)
 
1511
        if revision is not None:
 
1512
            revision_id = revision[0].as_revision_id(branch)
 
1513
        else:
 
1514
            revision_id = branch.last_revision()
 
1515
        if revision_id == _mod_revision.ensure_null(tree.last_revision()):
 
1516
            revno = branch.revision_id_to_dotted_revno(revision_id)
 
1517
            note("Tree is up to date at revision %s of branch %s" %
 
1518
                ('.'.join(map(str, revno)), branch_location))
 
1519
            return 0
 
1520
        view_info = _get_view_info_for_change_reporter(tree)
 
1521
        change_reporter = delta._ChangeReporter(
 
1522
            unversioned_filter=tree.is_ignored,
 
1523
            view_info=view_info)
998
1524
        try:
999
 
            existing_pending_merges = tree.get_parent_ids()[1:]
1000
 
            last_rev = tree.last_revision()
1001
 
            if last_rev == tree.branch.last_revision():
1002
 
                # may be up to date, check master too.
1003
 
                master = tree.branch.get_master_branch()
1004
 
                if master is None or last_rev == master.last_revision():
1005
 
                    revno = tree.branch.revision_id_to_revno(last_rev)
1006
 
                    note("Tree is up to date at revision %d." % (revno,))
1007
 
                    return 0
1008
 
            conflicts = tree.update()
1009
 
            revno = tree.branch.revision_id_to_revno(tree.last_revision())
1010
 
            note('Updated to revision %d.' % (revno,))
1011
 
            if tree.get_parent_ids()[1:] != existing_pending_merges:
1012
 
                note('Your local commits will now show as pending merges with '
1013
 
                     "'bzr status', and can be committed with 'bzr commit'.")
1014
 
            if conflicts != 0:
1015
 
                return 1
1016
 
            else:
1017
 
                return 0
1018
 
        finally:
1019
 
            tree.unlock()
 
1525
            conflicts = tree.update(
 
1526
                change_reporter,
 
1527
                possible_transports=possible_transports,
 
1528
                revision=revision_id,
 
1529
                old_tip=old_tip,
 
1530
                show_base=show_base)
 
1531
        except errors.NoSuchRevision, e:
 
1532
            raise errors.BzrCommandError(
 
1533
                                  "branch has no revision %s\n"
 
1534
                                  "bzr update --revision only works"
 
1535
                                  " for a revision in the branch history"
 
1536
                                  % (e.revision))
 
1537
        revno = tree.branch.revision_id_to_dotted_revno(
 
1538
            _mod_revision.ensure_null(tree.last_revision()))
 
1539
        note('Updated to revision %s of branch %s' %
 
1540
             ('.'.join(map(str, revno)), branch_location))
 
1541
        parent_ids = tree.get_parent_ids()
 
1542
        if parent_ids[1:] and parent_ids[1:] != existing_pending_merges:
 
1543
            note('Your local commits will now show as pending merges with '
 
1544
                 "'bzr status', and can be committed with 'bzr commit'.")
 
1545
        if conflicts != 0:
 
1546
            return 1
 
1547
        else:
 
1548
            return 0
1020
1549
 
1021
1550
 
1022
1551
class cmd_info(Command):
1023
 
    """Show information about a working tree, branch or repository.
 
1552
    __doc__ = """Show information about a working tree, branch or repository.
1024
1553
 
1025
1554
    This command will show all known locations and formats associated to the
1026
 
    tree, branch or repository.  Statistical information is included with
1027
 
    each report.
 
1555
    tree, branch or repository.
 
1556
 
 
1557
    In verbose mode, statistical information is included with each report.
 
1558
    To see extended statistic information, use a verbosity level of 2 or
 
1559
    higher by specifying the verbose option multiple times, e.g. -vv.
1028
1560
 
1029
1561
    Branches and working trees will also report any missing revisions.
 
1562
 
 
1563
    :Examples:
 
1564
 
 
1565
      Display information on the format and related locations:
 
1566
 
 
1567
        bzr info
 
1568
 
 
1569
      Display the above together with extended format information and
 
1570
      basic statistics (like the number of files in the working tree and
 
1571
      number of revisions in the branch and repository):
 
1572
 
 
1573
        bzr info -v
 
1574
 
 
1575
      Display the above together with number of committers to the branch:
 
1576
 
 
1577
        bzr info -vv
1030
1578
    """
 
1579
    _see_also = ['revno', 'working-trees', 'repositories']
1031
1580
    takes_args = ['location?']
1032
1581
    takes_options = ['verbose']
 
1582
    encoding_type = 'replace'
1033
1583
 
1034
1584
    @display_command
1035
1585
    def run(self, location=None, verbose=False):
 
1586
        if verbose:
 
1587
            noise_level = get_verbosity_level()
 
1588
        else:
 
1589
            noise_level = 0
1036
1590
        from bzrlib.info import show_bzrdir_info
1037
1591
        show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1038
 
                         verbose=verbose)
 
1592
                         verbose=noise_level, outfile=self.outf)
1039
1593
 
1040
1594
 
1041
1595
class cmd_remove(Command):
1042
 
    """Make a file unversioned.
1043
 
 
1044
 
    This makes bzr stop tracking changes to a versioned file.  It does
1045
 
    not delete the working copy.
1046
 
 
1047
 
    You can specify one or more files, and/or --new.  If you specify --new,
1048
 
    only 'added' files will be removed.  If you specify both, then new files
1049
 
    in the specified directories will be removed.  If the directories are
1050
 
    also new, they will also be removed.
 
1596
    __doc__ = """Remove files or directories.
 
1597
 
 
1598
    This makes Bazaar stop tracking changes to the specified files. Bazaar will
 
1599
    delete them if they can easily be recovered using revert otherwise they
 
1600
    will be backed up (adding an extention of the form .~#~). If no options or
 
1601
    parameters are given Bazaar will scan for files that are being tracked by
 
1602
    Bazaar but missing in your tree and stop tracking them for you.
1051
1603
    """
1052
1604
    takes_args = ['file*']
1053
 
    takes_options = ['verbose', Option('new', help='remove newly-added files')]
1054
 
    aliases = ['rm']
 
1605
    takes_options = ['verbose',
 
1606
        Option('new', help='Only remove files that have never been committed.'),
 
1607
        RegistryOption.from_kwargs('file-deletion-strategy',
 
1608
            'The file deletion mode to be used.',
 
1609
            title='Deletion Strategy', value_switches=True, enum_switch=False,
 
1610
            safe='Backup changed files (default).',
 
1611
            keep='Delete from bzr but leave the working copy.',
 
1612
            no_backup='Don\'t backup changed files.',
 
1613
            force='Delete all the specified files, even if they can not be '
 
1614
                'recovered and even if they are non-empty directories. '
 
1615
                '(deprecated, use no-backup)')]
 
1616
    aliases = ['rm', 'del']
1055
1617
    encoding_type = 'replace'
1056
 
    
1057
 
    def run(self, file_list, verbose=False, new=False):
1058
 
        tree, file_list = tree_files(file_list)
1059
 
        if new is False:
1060
 
            if file_list is None:
1061
 
                raise errors.BzrCommandError('Specify one or more files to'
1062
 
                                             ' remove, or use --new.')
1063
 
        else:
 
1618
 
 
1619
    def run(self, file_list, verbose=False, new=False,
 
1620
        file_deletion_strategy='safe'):
 
1621
        if file_deletion_strategy == 'force':
 
1622
            note("(The --force option is deprecated, rather use --no-backup "
 
1623
                "in future.)")
 
1624
            file_deletion_strategy = 'no-backup'
 
1625
 
 
1626
        tree, file_list = WorkingTree.open_containing_paths(file_list)
 
1627
 
 
1628
        if file_list is not None:
 
1629
            file_list = [f for f in file_list]
 
1630
 
 
1631
        self.add_cleanup(tree.lock_write().unlock)
 
1632
        # Heuristics should probably all move into tree.remove_smart or
 
1633
        # some such?
 
1634
        if new:
1064
1635
            added = tree.changes_from(tree.basis_tree(),
1065
1636
                specific_files=file_list).added
1066
1637
            file_list = sorted([f[0] for f in added], reverse=True)
1067
1638
            if len(file_list) == 0:
1068
1639
                raise errors.BzrCommandError('No matching files.')
1069
 
        tree.remove(file_list, verbose=verbose, to_file=self.outf)
 
1640
        elif file_list is None:
 
1641
            # missing files show up in iter_changes(basis) as
 
1642
            # versioned-with-no-kind.
 
1643
            missing = []
 
1644
            for change in tree.iter_changes(tree.basis_tree()):
 
1645
                # Find paths in the working tree that have no kind:
 
1646
                if change[1][1] is not None and change[6][1] is None:
 
1647
                    missing.append(change[1][1])
 
1648
            file_list = sorted(missing, reverse=True)
 
1649
            file_deletion_strategy = 'keep'
 
1650
        tree.remove(file_list, verbose=verbose, to_file=self.outf,
 
1651
            keep_files=file_deletion_strategy=='keep',
 
1652
            force=(file_deletion_strategy=='no-backup'))
1070
1653
 
1071
1654
 
1072
1655
class cmd_file_id(Command):
1073
 
    """Print file_id of a particular file or directory.
 
1656
    __doc__ = """Print file_id of a particular file or directory.
1074
1657
 
1075
1658
    The file_id is assigned when the file is first added and remains the
1076
1659
    same through all revisions where the file exists, even when it is
1078
1661
    """
1079
1662
 
1080
1663
    hidden = True
 
1664
    _see_also = ['inventory', 'ls']
1081
1665
    takes_args = ['filename']
1082
1666
 
1083
1667
    @display_command
1084
1668
    def run(self, filename):
1085
1669
        tree, relpath = WorkingTree.open_containing(filename)
1086
 
        i = tree.inventory.path2id(relpath)
 
1670
        i = tree.path2id(relpath)
1087
1671
        if i is None:
1088
1672
            raise errors.NotVersionedError(filename)
1089
1673
        else:
1091
1675
 
1092
1676
 
1093
1677
class cmd_file_path(Command):
1094
 
    """Print path of file_ids to a file or directory.
 
1678
    __doc__ = """Print path of file_ids to a file or directory.
1095
1679
 
1096
1680
    This prints one line for each directory down to the target,
1097
1681
    starting at the branch root.
1103
1687
    @display_command
1104
1688
    def run(self, filename):
1105
1689
        tree, relpath = WorkingTree.open_containing(filename)
1106
 
        inv = tree.inventory
1107
 
        fid = inv.path2id(relpath)
 
1690
        fid = tree.path2id(relpath)
1108
1691
        if fid is None:
1109
1692
            raise errors.NotVersionedError(filename)
1110
 
        for fip in inv.get_idpath(fid):
1111
 
            self.outf.write(fip + '\n')
 
1693
        segments = osutils.splitpath(relpath)
 
1694
        for pos in range(1, len(segments) + 1):
 
1695
            path = osutils.joinpath(segments[:pos])
 
1696
            self.outf.write("%s\n" % tree.path2id(path))
1112
1697
 
1113
1698
 
1114
1699
class cmd_reconcile(Command):
1115
 
    """Reconcile bzr metadata in a branch.
 
1700
    __doc__ = """Reconcile bzr metadata in a branch.
1116
1701
 
1117
1702
    This can correct data mismatches that may have been caused by
1118
1703
    previous ghost operations or bzr upgrades. You should only
1119
 
    need to run this command if 'bzr check' or a bzr developer 
 
1704
    need to run this command if 'bzr check' or a bzr developer
1120
1705
    advises you to run it.
1121
1706
 
1122
1707
    If a second branch is provided, cross-branch reconciliation is
1124
1709
    id which was not present in very early bzr versions is represented
1125
1710
    correctly in both branches.
1126
1711
 
1127
 
    At the same time it is run it may recompress data resulting in 
 
1712
    At the same time it is run it may recompress data resulting in
1128
1713
    a potential saving in disk space or performance gain.
1129
1714
 
1130
1715
    The branch *MUST* be on a listable system such as local disk or sftp.
1131
1716
    """
 
1717
 
 
1718
    _see_also = ['check']
1132
1719
    takes_args = ['branch?']
 
1720
    takes_options = [
 
1721
        Option('canonicalize-chks',
 
1722
               help='Make sure CHKs are in canonical form (repairs '
 
1723
                    'bug 522637).',
 
1724
               hidden=True),
 
1725
        ]
1133
1726
 
1134
 
    def run(self, branch="."):
 
1727
    def run(self, branch=".", canonicalize_chks=False):
1135
1728
        from bzrlib.reconcile import reconcile
1136
1729
        dir = bzrdir.BzrDir.open(branch)
1137
 
        reconcile(dir)
 
1730
        reconcile(dir, canonicalize_chks=canonicalize_chks)
1138
1731
 
1139
1732
 
1140
1733
class cmd_revision_history(Command):
1141
 
    """Display the list of revision ids on a branch."""
 
1734
    __doc__ = """Display the list of revision ids on a branch."""
 
1735
 
 
1736
    _see_also = ['log']
1142
1737
    takes_args = ['location?']
1143
1738
 
1144
1739
    hidden = True
1152
1747
 
1153
1748
 
1154
1749
class cmd_ancestry(Command):
1155
 
    """List all revisions merged into this branch."""
 
1750
    __doc__ = """List all revisions merged into this branch."""
 
1751
 
 
1752
    _see_also = ['log', 'revision-history']
1156
1753
    takes_args = ['location?']
1157
1754
 
1158
1755
    hidden = True
1168
1765
            b = wt.branch
1169
1766
            last_revision = wt.last_revision()
1170
1767
 
1171
 
        revision_ids = b.repository.get_ancestry(last_revision)
1172
 
        assert revision_ids[0] is None
1173
 
        revision_ids.pop(0)
1174
 
        for revision_id in revision_ids:
 
1768
        self.add_cleanup(b.repository.lock_read().unlock)
 
1769
        graph = b.repository.get_graph()
 
1770
        revisions = [revid for revid, parents in
 
1771
            graph.iter_ancestry([last_revision])]
 
1772
        for revision_id in reversed(revisions):
 
1773
            if _mod_revision.is_null(revision_id):
 
1774
                continue
1175
1775
            self.outf.write(revision_id + '\n')
1176
1776
 
1177
1777
 
1178
1778
class cmd_init(Command):
1179
 
    """Make a directory into a versioned branch.
 
1779
    __doc__ = """Make a directory into a versioned branch.
1180
1780
 
1181
1781
    Use this to create an empty branch, or before importing an
1182
1782
    existing project.
1183
1783
 
1184
 
    If there is a repository in a parent directory of the location, then 
 
1784
    If there is a repository in a parent directory of the location, then
1185
1785
    the history of the branch will be stored in the repository.  Otherwise
1186
 
    init creates a standalone branch which carries its own history in 
1187
 
    .bzr.
 
1786
    init creates a standalone branch which carries its own history
 
1787
    in the .bzr directory.
1188
1788
 
1189
1789
    If there is already a branch at the location but it has no working tree,
1190
1790
    the tree can be populated with 'bzr checkout'.
1191
1791
 
1192
 
    Recipe for importing a tree of files:
 
1792
    Recipe for importing a tree of files::
 
1793
 
1193
1794
        cd ~/project
1194
1795
        bzr init
1195
1796
        bzr add .
1196
1797
        bzr status
1197
 
        bzr commit -m 'imported project'
 
1798
        bzr commit -m "imported project"
1198
1799
    """
 
1800
 
 
1801
    _see_also = ['init-repository', 'branch', 'checkout']
1199
1802
    takes_args = ['location?']
1200
1803
    takes_options = [
 
1804
        Option('create-prefix',
 
1805
               help='Create the path leading up to the branch '
 
1806
                    'if it does not already exist.'),
1201
1807
         RegistryOption('format',
1202
1808
                help='Specify a format for this branch. '
1203
1809
                'See "help formats".',
1204
 
                registry=bzrdir.format_registry,
1205
 
                converter=bzrdir.format_registry.make_bzrdir,
 
1810
                lazy_registry=('bzrlib.bzrdir', 'format_registry'),
 
1811
                converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1206
1812
                value_switches=True,
1207
 
                title="Branch Format",
 
1813
                title="Branch format",
1208
1814
                ),
1209
1815
         Option('append-revisions-only',
1210
1816
                help='Never change revnos or the existing log.'
1211
 
                '  Append revisions to it only.')
 
1817
                '  Append revisions to it only.'),
 
1818
         Option('no-tree',
 
1819
                'Create a branch without a working tree.')
1212
1820
         ]
1213
 
    def run(self, location=None, format=None, append_revisions_only=False):
 
1821
    def run(self, location=None, format=None, append_revisions_only=False,
 
1822
            create_prefix=False, no_tree=False):
1214
1823
        if format is None:
1215
1824
            format = bzrdir.format_registry.make_bzrdir('default')
1216
1825
        if location is None:
1223
1832
        # Just using os.mkdir, since I don't
1224
1833
        # believe that we want to create a bunch of
1225
1834
        # locations if the user supplies an extended path
1226
 
        # TODO: create-prefix
1227
 
        try:
1228
 
            to_transport.mkdir('.')
1229
 
        except errors.FileExists:
1230
 
            pass
1231
 
                    
1232
 
        try:
1233
 
            existing_bzrdir = bzrdir.BzrDir.open(location)
 
1835
        try:
 
1836
            to_transport.ensure_base()
 
1837
        except errors.NoSuchFile:
 
1838
            if not create_prefix:
 
1839
                raise errors.BzrCommandError("Parent directory of %s"
 
1840
                    " does not exist."
 
1841
                    "\nYou may supply --create-prefix to create all"
 
1842
                    " leading parent directories."
 
1843
                    % location)
 
1844
            to_transport.create_prefix()
 
1845
 
 
1846
        try:
 
1847
            a_bzrdir = bzrdir.BzrDir.open_from_transport(to_transport)
1234
1848
        except errors.NotBranchError:
1235
1849
            # really a NotBzrDir error...
1236
 
            branch = bzrdir.BzrDir.create_branch_convenience(location,
1237
 
                                                             format=format)
 
1850
            create_branch = bzrdir.BzrDir.create_branch_convenience
 
1851
            if no_tree:
 
1852
                force_new_tree = False
 
1853
            else:
 
1854
                force_new_tree = None
 
1855
            branch = create_branch(to_transport.base, format=format,
 
1856
                                   possible_transports=[to_transport],
 
1857
                                   force_new_tree=force_new_tree)
 
1858
            a_bzrdir = branch.bzrdir
1238
1859
        else:
1239
1860
            from bzrlib.transport.local import LocalTransport
1240
 
            if existing_bzrdir.has_branch():
 
1861
            if a_bzrdir.has_branch():
1241
1862
                if (isinstance(to_transport, LocalTransport)
1242
 
                    and not existing_bzrdir.has_workingtree()):
 
1863
                    and not a_bzrdir.has_workingtree()):
1243
1864
                        raise errors.BranchExistsWithoutWorkingTree(location)
1244
1865
                raise errors.AlreadyBranchError(location)
1245
 
            else:
1246
 
                branch = existing_bzrdir.create_branch()
1247
 
                existing_bzrdir.create_workingtree()
 
1866
            branch = a_bzrdir.create_branch()
 
1867
            if not no_tree:
 
1868
                a_bzrdir.create_workingtree()
1248
1869
        if append_revisions_only:
1249
1870
            try:
1250
1871
                branch.set_append_revisions_only(True)
1251
1872
            except errors.UpgradeRequired:
1252
1873
                raise errors.BzrCommandError('This branch format cannot be set'
1253
 
                    ' to append-revisions-only.  Try --experimental-branch6')
 
1874
                    ' to append-revisions-only.  Try --default.')
 
1875
        if not is_quiet():
 
1876
            from bzrlib.info import describe_layout, describe_format
 
1877
            try:
 
1878
                tree = a_bzrdir.open_workingtree(recommend_upgrade=False)
 
1879
            except (errors.NoWorkingTree, errors.NotLocalUrl):
 
1880
                tree = None
 
1881
            repository = branch.repository
 
1882
            layout = describe_layout(repository, branch, tree).lower()
 
1883
            format = describe_format(a_bzrdir, repository, branch, tree)
 
1884
            self.outf.write("Created a %s (format: %s)\n" % (layout, format))
 
1885
            if repository.is_shared():
 
1886
                #XXX: maybe this can be refactored into transport.path_or_url()
 
1887
                url = repository.bzrdir.root_transport.external_url()
 
1888
                try:
 
1889
                    url = urlutils.local_path_from_url(url)
 
1890
                except errors.InvalidURL:
 
1891
                    pass
 
1892
                self.outf.write("Using shared repository: %s\n" % url)
1254
1893
 
1255
1894
 
1256
1895
class cmd_init_repository(Command):
1257
 
    """Create a shared repository to hold branches.
1258
 
 
1259
 
    New branches created under the repository directory will store their revisions
1260
 
    in the repository, not in the branch directory, if the branch format supports
1261
 
    shared storage.
1262
 
 
1263
 
    example:
1264
 
        bzr init-repo repo
1265
 
        bzr init repo/trunk
1266
 
        bzr checkout --lightweight repo/trunk trunk-checkout
1267
 
        cd trunk-checkout
1268
 
        (add files here)
 
1896
    __doc__ = """Create a shared repository for branches to share storage space.
 
1897
 
 
1898
    New branches created under the repository directory will store their
 
1899
    revisions in the repository, not in the branch directory.  For branches
 
1900
    with shared history, this reduces the amount of storage needed and 
 
1901
    speeds up the creation of new branches.
 
1902
 
 
1903
    If the --no-trees option is given then the branches in the repository
 
1904
    will not have working trees by default.  They will still exist as 
 
1905
    directories on disk, but they will not have separate copies of the 
 
1906
    files at a certain revision.  This can be useful for repositories that
 
1907
    store branches which are interacted with through checkouts or remote
 
1908
    branches, such as on a server.
 
1909
 
 
1910
    :Examples:
 
1911
        Create a shared repository holding just branches::
 
1912
 
 
1913
            bzr init-repo --no-trees repo
 
1914
            bzr init repo/trunk
 
1915
 
 
1916
        Make a lightweight checkout elsewhere::
 
1917
 
 
1918
            bzr checkout --lightweight repo/trunk trunk-checkout
 
1919
            cd trunk-checkout
 
1920
            (add files here)
1269
1921
    """
 
1922
 
 
1923
    _see_also = ['init', 'branch', 'checkout', 'repositories']
1270
1924
    takes_args = ["location"]
1271
1925
    takes_options = [RegistryOption('format',
1272
1926
                            help='Specify a format for this repository. See'
1273
 
                                 ' "bzr help formats" for details',
1274
 
                            registry=bzrdir.format_registry,
1275
 
                            converter=bzrdir.format_registry.make_bzrdir,
 
1927
                                 ' "bzr help formats" for details.',
 
1928
                            lazy_registry=('bzrlib.bzrdir', 'format_registry'),
 
1929
                            converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
1276
1930
                            value_switches=True, title='Repository format'),
1277
 
                     Option('trees',
1278
 
                             help='Allows branches in repository to have'
1279
 
                             ' a working tree')]
 
1931
                     Option('no-trees',
 
1932
                             help='Branches in the repository will default to'
 
1933
                                  ' not having a working tree.'),
 
1934
                    ]
1280
1935
    aliases = ["init-repo"]
1281
 
    def run(self, location, format=None, trees=False):
 
1936
 
 
1937
    def run(self, location, format=None, no_trees=False):
1282
1938
        if format is None:
1283
1939
            format = bzrdir.format_registry.make_bzrdir('default')
1284
1940
 
1286
1942
            location = '.'
1287
1943
 
1288
1944
        to_transport = transport.get_transport(location)
1289
 
        try:
1290
 
            to_transport.mkdir('.')
1291
 
        except errors.FileExists:
1292
 
            pass
 
1945
        to_transport.ensure_base()
1293
1946
 
1294
1947
        newdir = format.initialize_on_transport(to_transport)
1295
1948
        repo = newdir.create_repository(shared=True)
1296
 
        repo.set_make_working_trees(trees)
 
1949
        repo.set_make_working_trees(not no_trees)
 
1950
        if not is_quiet():
 
1951
            from bzrlib.info import show_bzrdir_info
 
1952
            show_bzrdir_info(repo.bzrdir, verbose=0, outfile=self.outf)
1297
1953
 
1298
1954
 
1299
1955
class cmd_diff(Command):
1300
 
    """Show differences in the working tree or between revisions.
1301
 
    
1302
 
    If files are listed, only the changes in those files are listed.
1303
 
    Otherwise, all changes for the tree are listed.
 
1956
    __doc__ = """Show differences in the working tree, between revisions or branches.
 
1957
 
 
1958
    If no arguments are given, all changes for the current tree are listed.
 
1959
    If files are given, only the changes in those files are listed.
 
1960
    Remote and multiple branches can be compared by using the --old and
 
1961
    --new options. If not provided, the default for both is derived from
 
1962
    the first argument, if any, or the current tree if no arguments are
 
1963
    given.
1304
1964
 
1305
1965
    "bzr diff -p1" is equivalent to "bzr diff --prefix old/:new/", and
1306
1966
    produces patches suitable for "patch -p1".
1307
1967
 
1308
 
    examples:
1309
 
        bzr diff
1310
 
            Shows the difference in the working tree versus the last commit
1311
 
        bzr diff -r1
1312
 
            Difference between the working tree and revision 1
1313
 
        bzr diff -r1..2
1314
 
            Difference between revision 2 and revision 1
1315
 
        bzr diff --diff-prefix old/:new/
1316
 
            Same as 'bzr diff' but prefix paths with old/ and new/
1317
 
        bzr diff bzr.mine bzr.dev
1318
 
            Show the differences between the two working trees
1319
 
        bzr diff foo.c
1320
 
            Show just the differences for 'foo.c'
 
1968
    Note that when using the -r argument with a range of revisions, the
 
1969
    differences are computed between the two specified revisions.  That
 
1970
    is, the command does not show the changes introduced by the first 
 
1971
    revision in the range.  This differs from the interpretation of 
 
1972
    revision ranges used by "bzr log" which includes the first revision
 
1973
    in the range.
 
1974
 
 
1975
    :Exit values:
 
1976
        1 - changed
 
1977
        2 - unrepresentable changes
 
1978
        3 - error
 
1979
        0 - no change
 
1980
 
 
1981
    :Examples:
 
1982
        Shows the difference in the working tree versus the last commit::
 
1983
 
 
1984
            bzr diff
 
1985
 
 
1986
        Difference between the working tree and revision 1::
 
1987
 
 
1988
            bzr diff -r1
 
1989
 
 
1990
        Difference between revision 3 and revision 1::
 
1991
 
 
1992
            bzr diff -r1..3
 
1993
 
 
1994
        Difference between revision 3 and revision 1 for branch xxx::
 
1995
 
 
1996
            bzr diff -r1..3 xxx
 
1997
 
 
1998
        The changes introduced by revision 2 (equivalent to -r1..2)::
 
1999
 
 
2000
            bzr diff -c2
 
2001
 
 
2002
        To see the changes introduced by revision X::
 
2003
        
 
2004
            bzr diff -cX
 
2005
 
 
2006
        Note that in the case of a merge, the -c option shows the changes
 
2007
        compared to the left hand parent. To see the changes against
 
2008
        another parent, use::
 
2009
 
 
2010
            bzr diff -r<chosen_parent>..X
 
2011
 
 
2012
        The changes between the current revision and the previous revision
 
2013
        (equivalent to -c-1 and -r-2..-1)
 
2014
 
 
2015
            bzr diff -r-2..
 
2016
 
 
2017
        Show just the differences for file NEWS::
 
2018
 
 
2019
            bzr diff NEWS
 
2020
 
 
2021
        Show the differences in working tree xxx for file NEWS::
 
2022
 
 
2023
            bzr diff xxx/NEWS
 
2024
 
 
2025
        Show the differences from branch xxx to this working tree:
 
2026
 
 
2027
            bzr diff --old xxx
 
2028
 
 
2029
        Show the differences between two branches for file NEWS::
 
2030
 
 
2031
            bzr diff --old xxx --new yyy NEWS
 
2032
 
 
2033
        Same as 'bzr diff' but prefix paths with old/ and new/::
 
2034
 
 
2035
            bzr diff --prefix old/:new/
 
2036
            
 
2037
        Show the differences using a custom diff program with options::
 
2038
        
 
2039
            bzr diff --using /usr/bin/diff --diff-options -wu
1321
2040
    """
1322
 
    # TODO: Option to use external diff command; could be GNU diff, wdiff,
1323
 
    #       or a graphical diff.
1324
 
 
1325
 
    # TODO: Python difflib is not exactly the same as unidiff; should
1326
 
    #       either fix it up or prefer to use an external diff.
1327
 
 
1328
 
    # TODO: Selected-file diff is inefficient and doesn't show you
1329
 
    #       deleted files.
1330
 
 
1331
 
    # TODO: This probably handles non-Unix newlines poorly.
1332
 
 
 
2041
    _see_also = ['status']
1333
2042
    takes_args = ['file*']
1334
 
    takes_options = ['revision', 'diff-options',
 
2043
    takes_options = [
 
2044
        Option('diff-options', type=str,
 
2045
               help='Pass these options to the external diff program.'),
1335
2046
        Option('prefix', type=str,
1336
2047
               short_name='p',
1337
 
               help='Set prefixes to added to old and new filenames, as '
1338
 
                    'two values separated by a colon.'),
 
2048
               help='Set prefixes added to old and new filenames, as '
 
2049
                    'two values separated by a colon. (eg "old/:new/").'),
 
2050
        Option('old',
 
2051
            help='Branch/tree to compare from.',
 
2052
            type=unicode,
 
2053
            ),
 
2054
        Option('new',
 
2055
            help='Branch/tree to compare to.',
 
2056
            type=unicode,
 
2057
            ),
 
2058
        'revision',
 
2059
        'change',
 
2060
        Option('using',
 
2061
            help='Use this command to compare files.',
 
2062
            type=unicode,
 
2063
            ),
 
2064
        RegistryOption('format',
 
2065
            short_name='F',
 
2066
            help='Diff format to use.',
 
2067
            lazy_registry=('bzrlib.diff', 'format_registry'),
 
2068
            title='Diff format'),
1339
2069
        ]
1340
2070
    aliases = ['di', 'dif']
1341
2071
    encoding_type = 'exact'
1342
2072
 
1343
2073
    @display_command
1344
2074
    def run(self, revision=None, file_list=None, diff_options=None,
1345
 
            prefix=None):
1346
 
        from bzrlib.diff import diff_cmd_helper, show_diff_trees
 
2075
            prefix=None, old=None, new=None, using=None, format=None):
 
2076
        from bzrlib.diff import (get_trees_and_branches_to_diff_locked,
 
2077
            show_diff_trees)
1347
2078
 
1348
2079
        if (prefix is None) or (prefix == '0'):
1349
2080
            # diff -p0 format
1355
2086
        elif ':' in prefix:
1356
2087
            old_label, new_label = prefix.split(":")
1357
2088
        else:
1358
 
            raise BzrCommandError(
1359
 
                "--prefix expects two values separated by a colon")
 
2089
            raise errors.BzrCommandError(
 
2090
                '--prefix expects two values separated by a colon'
 
2091
                ' (eg "old/:new/")')
1360
2092
 
1361
2093
        if revision and len(revision) > 2:
1362
2094
            raise errors.BzrCommandError('bzr diff --revision takes exactly'
1363
2095
                                         ' one or two revision specifiers')
1364
 
        
1365
 
        try:
1366
 
            tree1, file_list = internal_tree_files(file_list)
1367
 
            tree2 = None
1368
 
            b = None
1369
 
            b2 = None
1370
 
        except errors.FileInWrongBranch:
1371
 
            if len(file_list) != 2:
1372
 
                raise errors.BzrCommandError("Files are in different branches")
1373
 
 
1374
 
            tree1, file1 = WorkingTree.open_containing(file_list[0])
1375
 
            tree2, file2 = WorkingTree.open_containing(file_list[1])
1376
 
            if file1 != "" or file2 != "":
1377
 
                # FIXME diff those two files. rbc 20051123
1378
 
                raise errors.BzrCommandError("Files are in different branches")
1379
 
            file_list = None
1380
 
        except errors.NotBranchError:
1381
 
            if (revision is not None and len(revision) == 2
1382
 
                and not revision[0].needs_branch()
1383
 
                and not revision[1].needs_branch()):
1384
 
                # If both revision specs include a branch, we can
1385
 
                # diff them without needing a local working tree
1386
 
                tree1, tree2 = None, None
1387
 
            else:
1388
 
                raise
1389
 
 
1390
 
        if tree2 is not None:
1391
 
            if revision is not None:
1392
 
                # FIXME: but there should be a clean way to diff between
1393
 
                # non-default versions of two trees, it's not hard to do
1394
 
                # internally...
1395
 
                raise errors.BzrCommandError(
1396
 
                        "Sorry, diffing arbitrary revisions across branches "
1397
 
                        "is not implemented yet")
1398
 
            return show_diff_trees(tree1, tree2, sys.stdout, 
1399
 
                                   specific_files=file_list,
1400
 
                                   external_diff_options=diff_options,
1401
 
                                   old_label=old_label, new_label=new_label)
1402
 
 
1403
 
        return diff_cmd_helper(tree1, file_list, diff_options,
1404
 
                               revision_specs=revision,
1405
 
                               old_label=old_label, new_label=new_label)
 
2096
 
 
2097
        if using is not None and format is not None:
 
2098
            raise errors.BzrCommandError('--using and --format are mutually '
 
2099
                'exclusive.')
 
2100
 
 
2101
        (old_tree, new_tree,
 
2102
         old_branch, new_branch,
 
2103
         specific_files, extra_trees) = get_trees_and_branches_to_diff_locked(
 
2104
            file_list, revision, old, new, self.add_cleanup, apply_view=True)
 
2105
        # GNU diff on Windows uses ANSI encoding for filenames
 
2106
        path_encoding = osutils.get_diff_header_encoding()
 
2107
        return show_diff_trees(old_tree, new_tree, sys.stdout,
 
2108
                               specific_files=specific_files,
 
2109
                               external_diff_options=diff_options,
 
2110
                               old_label=old_label, new_label=new_label,
 
2111
                               extra_trees=extra_trees,
 
2112
                               path_encoding=path_encoding,
 
2113
                               using=using,
 
2114
                               format_cls=format)
1406
2115
 
1407
2116
 
1408
2117
class cmd_deleted(Command):
1409
 
    """List files deleted in the working tree.
 
2118
    __doc__ = """List files deleted in the working tree.
1410
2119
    """
1411
2120
    # TODO: Show files deleted since a previous revision, or
1412
2121
    # between two revisions.
1414
2123
    # directories with readdir, rather than stating each one.  Same
1415
2124
    # level of effort but possibly much less IO.  (Or possibly not,
1416
2125
    # if the directories are very large...)
1417
 
    takes_options = ['show-ids']
 
2126
    _see_also = ['status', 'ls']
 
2127
    takes_options = ['directory', 'show-ids']
1418
2128
 
1419
2129
    @display_command
1420
 
    def run(self, show_ids=False):
1421
 
        tree = WorkingTree.open_containing(u'.')[0]
 
2130
    def run(self, show_ids=False, directory=u'.'):
 
2131
        tree = WorkingTree.open_containing(directory)[0]
 
2132
        self.add_cleanup(tree.lock_read().unlock)
1422
2133
        old = tree.basis_tree()
 
2134
        self.add_cleanup(old.lock_read().unlock)
1423
2135
        for path, ie in old.inventory.iter_entries():
1424
2136
            if not tree.has_id(ie.file_id):
1425
2137
                self.outf.write(path)
1430
2142
 
1431
2143
 
1432
2144
class cmd_modified(Command):
1433
 
    """List files modified in working tree.
1434
 
 
1435
 
    See also: "bzr status".
 
2145
    __doc__ = """List files modified in working tree.
1436
2146
    """
1437
2147
 
1438
2148
    hidden = True
 
2149
    _see_also = ['status', 'ls']
 
2150
    takes_options = ['directory', 'null']
1439
2151
 
1440
2152
    @display_command
1441
 
    def run(self):
1442
 
        tree = WorkingTree.open_containing(u'.')[0]
 
2153
    def run(self, null=False, directory=u'.'):
 
2154
        tree = WorkingTree.open_containing(directory)[0]
 
2155
        self.add_cleanup(tree.lock_read().unlock)
1443
2156
        td = tree.changes_from(tree.basis_tree())
 
2157
        self.cleanup_now()
1444
2158
        for path, id, kind, text_modified, meta_modified in td.modified:
1445
 
            self.outf.write(path + '\n')
 
2159
            if null:
 
2160
                self.outf.write(path + '\0')
 
2161
            else:
 
2162
                self.outf.write(osutils.quotefn(path) + '\n')
1446
2163
 
1447
2164
 
1448
2165
class cmd_added(Command):
1449
 
    """List files added in working tree.
1450
 
 
1451
 
    See also: "bzr status".
 
2166
    __doc__ = """List files added in working tree.
1452
2167
    """
1453
2168
 
1454
2169
    hidden = True
 
2170
    _see_also = ['status', 'ls']
 
2171
    takes_options = ['directory', 'null']
1455
2172
 
1456
2173
    @display_command
1457
 
    def run(self):
1458
 
        wt = WorkingTree.open_containing(u'.')[0]
1459
 
        basis_inv = wt.basis_tree().inventory
 
2174
    def run(self, null=False, directory=u'.'):
 
2175
        wt = WorkingTree.open_containing(directory)[0]
 
2176
        self.add_cleanup(wt.lock_read().unlock)
 
2177
        basis = wt.basis_tree()
 
2178
        self.add_cleanup(basis.lock_read().unlock)
 
2179
        basis_inv = basis.inventory
1460
2180
        inv = wt.inventory
1461
2181
        for file_id in inv:
1462
 
            if file_id in basis_inv:
 
2182
            if basis_inv.has_id(file_id):
1463
2183
                continue
1464
2184
            if inv.is_root(file_id) and len(basis_inv) == 0:
1465
2185
                continue
1466
2186
            path = inv.id2path(file_id)
1467
 
            if not os.access(osutils.abspath(path), os.F_OK):
 
2187
            if not os.access(osutils.pathjoin(wt.basedir, path), os.F_OK):
1468
2188
                continue
1469
 
            self.outf.write(path + '\n')
 
2189
            if null:
 
2190
                self.outf.write(path + '\0')
 
2191
            else:
 
2192
                self.outf.write(osutils.quotefn(path) + '\n')
1470
2193
 
1471
2194
 
1472
2195
class cmd_root(Command):
1473
 
    """Show the tree root directory.
 
2196
    __doc__ = """Show the tree root directory.
1474
2197
 
1475
2198
    The root is the nearest enclosing directory with a .bzr control
1476
2199
    directory."""
 
2200
 
1477
2201
    takes_args = ['filename?']
1478
2202
    @display_command
1479
2203
    def run(self, filename=None):
1482
2206
        self.outf.write(tree.basedir + '\n')
1483
2207
 
1484
2208
 
 
2209
def _parse_limit(limitstring):
 
2210
    try:
 
2211
        return int(limitstring)
 
2212
    except ValueError:
 
2213
        msg = "The limit argument must be an integer."
 
2214
        raise errors.BzrCommandError(msg)
 
2215
 
 
2216
 
 
2217
def _parse_levels(s):
 
2218
    try:
 
2219
        return int(s)
 
2220
    except ValueError:
 
2221
        msg = "The levels argument must be an integer."
 
2222
        raise errors.BzrCommandError(msg)
 
2223
 
 
2224
 
1485
2225
class cmd_log(Command):
1486
 
    """Show log of a branch, file, or directory.
1487
 
 
1488
 
    By default show the log of the branch containing the working directory.
1489
 
 
1490
 
    To request a range of logs, you can use the command -r begin..end
1491
 
    -r revision requests a specific revision, -r ..end or -r begin.. are
1492
 
    also valid.
1493
 
 
1494
 
    examples:
1495
 
        bzr log
1496
 
        bzr log foo.c
1497
 
        bzr log -r -10.. http://server/branch
 
2226
    __doc__ = """Show historical log for a branch or subset of a branch.
 
2227
 
 
2228
    log is bzr's default tool for exploring the history of a branch.
 
2229
    The branch to use is taken from the first parameter. If no parameters
 
2230
    are given, the branch containing the working directory is logged.
 
2231
    Here are some simple examples::
 
2232
 
 
2233
      bzr log                       log the current branch
 
2234
      bzr log foo.py                log a file in its branch
 
2235
      bzr log http://server/branch  log a branch on a server
 
2236
 
 
2237
    The filtering, ordering and information shown for each revision can
 
2238
    be controlled as explained below. By default, all revisions are
 
2239
    shown sorted (topologically) so that newer revisions appear before
 
2240
    older ones and descendants always appear before ancestors. If displayed,
 
2241
    merged revisions are shown indented under the revision in which they
 
2242
    were merged.
 
2243
 
 
2244
    :Output control:
 
2245
 
 
2246
      The log format controls how information about each revision is
 
2247
      displayed. The standard log formats are called ``long``, ``short``
 
2248
      and ``line``. The default is long. See ``bzr help log-formats``
 
2249
      for more details on log formats.
 
2250
 
 
2251
      The following options can be used to control what information is
 
2252
      displayed::
 
2253
 
 
2254
        -l N        display a maximum of N revisions
 
2255
        -n N        display N levels of revisions (0 for all, 1 for collapsed)
 
2256
        -v          display a status summary (delta) for each revision
 
2257
        -p          display a diff (patch) for each revision
 
2258
        --show-ids  display revision-ids (and file-ids), not just revnos
 
2259
 
 
2260
      Note that the default number of levels to display is a function of the
 
2261
      log format. If the -n option is not used, the standard log formats show
 
2262
      just the top level (mainline).
 
2263
 
 
2264
      Status summaries are shown using status flags like A, M, etc. To see
 
2265
      the changes explained using words like ``added`` and ``modified``
 
2266
      instead, use the -vv option.
 
2267
 
 
2268
    :Ordering control:
 
2269
 
 
2270
      To display revisions from oldest to newest, use the --forward option.
 
2271
      In most cases, using this option will have little impact on the total
 
2272
      time taken to produce a log, though --forward does not incrementally
 
2273
      display revisions like --reverse does when it can.
 
2274
 
 
2275
    :Revision filtering:
 
2276
 
 
2277
      The -r option can be used to specify what revision or range of revisions
 
2278
      to filter against. The various forms are shown below::
 
2279
 
 
2280
        -rX      display revision X
 
2281
        -rX..    display revision X and later
 
2282
        -r..Y    display up to and including revision Y
 
2283
        -rX..Y   display from X to Y inclusive
 
2284
 
 
2285
      See ``bzr help revisionspec`` for details on how to specify X and Y.
 
2286
      Some common examples are given below::
 
2287
 
 
2288
        -r-1                show just the tip
 
2289
        -r-10..             show the last 10 mainline revisions
 
2290
        -rsubmit:..         show what's new on this branch
 
2291
        -rancestor:path..   show changes since the common ancestor of this
 
2292
                            branch and the one at location path
 
2293
        -rdate:yesterday..  show changes since yesterday
 
2294
 
 
2295
      When logging a range of revisions using -rX..Y, log starts at
 
2296
      revision Y and searches back in history through the primary
 
2297
      ("left-hand") parents until it finds X. When logging just the
 
2298
      top level (using -n1), an error is reported if X is not found
 
2299
      along the way. If multi-level logging is used (-n0), X may be
 
2300
      a nested merge revision and the log will be truncated accordingly.
 
2301
 
 
2302
    :Path filtering:
 
2303
 
 
2304
      If parameters are given and the first one is not a branch, the log
 
2305
      will be filtered to show only those revisions that changed the
 
2306
      nominated files or directories.
 
2307
 
 
2308
      Filenames are interpreted within their historical context. To log a
 
2309
      deleted file, specify a revision range so that the file existed at
 
2310
      the end or start of the range.
 
2311
 
 
2312
      Historical context is also important when interpreting pathnames of
 
2313
      renamed files/directories. Consider the following example:
 
2314
 
 
2315
      * revision 1: add tutorial.txt
 
2316
      * revision 2: modify tutorial.txt
 
2317
      * revision 3: rename tutorial.txt to guide.txt; add tutorial.txt
 
2318
 
 
2319
      In this case:
 
2320
 
 
2321
      * ``bzr log guide.txt`` will log the file added in revision 1
 
2322
 
 
2323
      * ``bzr log tutorial.txt`` will log the new file added in revision 3
 
2324
 
 
2325
      * ``bzr log -r2 -p tutorial.txt`` will show the changes made to
 
2326
        the original file in revision 2.
 
2327
 
 
2328
      * ``bzr log -r2 -p guide.txt`` will display an error message as there
 
2329
        was no file called guide.txt in revision 2.
 
2330
 
 
2331
      Renames are always followed by log. By design, there is no need to
 
2332
      explicitly ask for this (and no way to stop logging a file back
 
2333
      until it was last renamed).
 
2334
 
 
2335
    :Other filtering:
 
2336
 
 
2337
      The --match option can be used for finding revisions that match a
 
2338
      regular expression in a commit message, committer, author or bug.
 
2339
      Specifying the option several times will match any of the supplied
 
2340
      expressions. --match-author, --match-bugs, --match-committer and
 
2341
      --match-message can be used to only match a specific field.
 
2342
 
 
2343
    :Tips & tricks:
 
2344
 
 
2345
      GUI tools and IDEs are often better at exploring history than command
 
2346
      line tools: you may prefer qlog or viz from qbzr or bzr-gtk, the
 
2347
      bzr-explorer shell, or the Loggerhead web interface.  See the Plugin
 
2348
      Guide <http://doc.bazaar.canonical.com/plugins/en/> and
 
2349
      <http://wiki.bazaar.canonical.com/IDEIntegration>.  
 
2350
 
 
2351
      You may find it useful to add the aliases below to ``bazaar.conf``::
 
2352
 
 
2353
        [ALIASES]
 
2354
        tip = log -r-1
 
2355
        top = log -l10 --line
 
2356
        show = log -v -p
 
2357
 
 
2358
      ``bzr tip`` will then show the latest revision while ``bzr top``
 
2359
      will show the last 10 mainline revisions. To see the details of a
 
2360
      particular revision X,  ``bzr show -rX``.
 
2361
 
 
2362
      If you are interested in looking deeper into a particular merge X,
 
2363
      use ``bzr log -n0 -rX``.
 
2364
 
 
2365
      ``bzr log -v`` on a branch with lots of history is currently
 
2366
      very slow. A fix for this issue is currently under development.
 
2367
      With or without that fix, it is recommended that a revision range
 
2368
      be given when using the -v option.
 
2369
 
 
2370
      bzr has a generic full-text matching plugin, bzr-search, that can be
 
2371
      used to find revisions matching user names, commit messages, etc.
 
2372
      Among other features, this plugin can find all revisions containing
 
2373
      a list of words but not others.
 
2374
 
 
2375
      When exploring non-mainline history on large projects with deep
 
2376
      history, the performance of log can be greatly improved by installing
 
2377
      the historycache plugin. This plugin buffers historical information
 
2378
      trading disk space for faster speed.
1498
2379
    """
1499
 
 
1500
 
    # TODO: Make --revision support uuid: and hash: [future tag:] notation.
1501
 
 
1502
 
    takes_args = ['location?']
1503
 
    takes_options = [Option('forward', 
1504
 
                            help='show from oldest to newest'),
1505
 
                     'timezone', 
1506
 
                     Option('verbose', 
1507
 
                             short_name='v',
1508
 
                             help='show files changed in each revision'),
1509
 
                     'show-ids', 'revision',
1510
 
                     'log-format',
1511
 
                     Option('message',
1512
 
                            short_name='m',
1513
 
                            help='show revisions whose message matches this regexp',
1514
 
                            type=str),
1515
 
                     ]
 
2380
    takes_args = ['file*']
 
2381
    _see_also = ['log-formats', 'revisionspec']
 
2382
    takes_options = [
 
2383
            Option('forward',
 
2384
                   help='Show from oldest to newest.'),
 
2385
            'timezone',
 
2386
            custom_help('verbose',
 
2387
                   help='Show files changed in each revision.'),
 
2388
            'show-ids',
 
2389
            'revision',
 
2390
            Option('change',
 
2391
                   type=bzrlib.option._parse_revision_str,
 
2392
                   short_name='c',
 
2393
                   help='Show just the specified revision.'
 
2394
                   ' See also "help revisionspec".'),
 
2395
            'log-format',
 
2396
            RegistryOption('authors',
 
2397
                'What names to list as authors - first, all or committer.',
 
2398
                title='Authors',
 
2399
                lazy_registry=('bzrlib.log', 'author_list_registry'),
 
2400
            ),
 
2401
            Option('levels',
 
2402
                   short_name='n',
 
2403
                   help='Number of levels to display - 0 for all, 1 for flat.',
 
2404
                   argname='N',
 
2405
                   type=_parse_levels),
 
2406
            Option('message',
 
2407
                   help='Show revisions whose message matches this '
 
2408
                        'regular expression.',
 
2409
                   type=str,
 
2410
                   hidden=True),
 
2411
            Option('limit',
 
2412
                   short_name='l',
 
2413
                   help='Limit the output to the first N revisions.',
 
2414
                   argname='N',
 
2415
                   type=_parse_limit),
 
2416
            Option('show-diff',
 
2417
                   short_name='p',
 
2418
                   help='Show changes made in each revision as a patch.'),
 
2419
            Option('include-merges',
 
2420
                   help='Show merged revisions like --levels 0 does.'),
 
2421
            Option('exclude-common-ancestry',
 
2422
                   help='Display only the revisions that are not part'
 
2423
                   ' of both ancestries (require -rX..Y)'
 
2424
                   ),
 
2425
            Option('signatures',
 
2426
                   help='Show digital signature validity'),
 
2427
            ListOption('match',
 
2428
                short_name='m',
 
2429
                help='Show revisions whose properties match this '
 
2430
                'expression.',
 
2431
                type=str),
 
2432
            ListOption('match-message',
 
2433
                   help='Show revisions whose message matches this '
 
2434
                   'expression.',
 
2435
                type=str),
 
2436
            ListOption('match-committer',
 
2437
                   help='Show revisions whose committer matches this '
 
2438
                   'expression.',
 
2439
                type=str),
 
2440
            ListOption('match-author',
 
2441
                   help='Show revisions whose authors match this '
 
2442
                   'expression.',
 
2443
                type=str),
 
2444
            ListOption('match-bugs',
 
2445
                   help='Show revisions whose bugs match this '
 
2446
                   'expression.',
 
2447
                type=str)
 
2448
            ]
1516
2449
    encoding_type = 'replace'
1517
2450
 
1518
2451
    @display_command
1519
 
    def run(self, location=None, timezone='original',
 
2452
    def run(self, file_list=None, timezone='original',
1520
2453
            verbose=False,
1521
2454
            show_ids=False,
1522
2455
            forward=False,
1523
2456
            revision=None,
 
2457
            change=None,
1524
2458
            log_format=None,
1525
 
            message=None):
1526
 
        from bzrlib.log import show_log
1527
 
        assert message is None or isinstance(message, basestring), \
1528
 
            "invalid message argument %r" % message
 
2459
            levels=None,
 
2460
            message=None,
 
2461
            limit=None,
 
2462
            show_diff=False,
 
2463
            include_merges=False,
 
2464
            authors=None,
 
2465
            exclude_common_ancestry=False,
 
2466
            signatures=False,
 
2467
            match=None,
 
2468
            match_message=None,
 
2469
            match_committer=None,
 
2470
            match_author=None,
 
2471
            match_bugs=None,
 
2472
            ):
 
2473
        from bzrlib.log import (
 
2474
            Logger,
 
2475
            make_log_request_dict,
 
2476
            _get_info_for_log_files,
 
2477
            )
1529
2478
        direction = (forward and 'forward') or 'reverse'
1530
 
        
1531
 
        # log everything
1532
 
        file_id = None
1533
 
        if location:
1534
 
            # find the file id to log:
1535
 
 
1536
 
            tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1537
 
                location)
1538
 
            if fp != '':
1539
 
                if tree is None:
1540
 
                    tree = b.basis_tree()
1541
 
                inv = tree.inventory
1542
 
                file_id = inv.path2id(fp)
 
2479
        if (exclude_common_ancestry
 
2480
            and (revision is None or len(revision) != 2)):
 
2481
            raise errors.BzrCommandError(
 
2482
                '--exclude-common-ancestry requires -r with two revisions')
 
2483
        if include_merges:
 
2484
            if levels is None:
 
2485
                levels = 0
 
2486
            else:
 
2487
                raise errors.BzrCommandError(
 
2488
                    '--levels and --include-merges are mutually exclusive')
 
2489
 
 
2490
        if change is not None:
 
2491
            if len(change) > 1:
 
2492
                raise errors.RangeInChangeOption()
 
2493
            if revision is not None:
 
2494
                raise errors.BzrCommandError(
 
2495
                    '--revision and --change are mutually exclusive')
 
2496
            else:
 
2497
                revision = change
 
2498
 
 
2499
        file_ids = []
 
2500
        filter_by_dir = False
 
2501
        if file_list:
 
2502
            # find the file ids to log and check for directory filtering
 
2503
            b, file_info_list, rev1, rev2 = _get_info_for_log_files(
 
2504
                revision, file_list, self.add_cleanup)
 
2505
            for relpath, file_id, kind in file_info_list:
1543
2506
                if file_id is None:
1544
2507
                    raise errors.BzrCommandError(
1545
 
                        "Path does not have any revision history: %s" %
1546
 
                        location)
 
2508
                        "Path unknown at end or start of revision range: %s" %
 
2509
                        relpath)
 
2510
                # If the relpath is the top of the tree, we log everything
 
2511
                if relpath == '':
 
2512
                    file_ids = []
 
2513
                    break
 
2514
                else:
 
2515
                    file_ids.append(file_id)
 
2516
                filter_by_dir = filter_by_dir or (
 
2517
                    kind in ['directory', 'tree-reference'])
1547
2518
        else:
1548
 
            # local dir only
1549
 
            # FIXME ? log the current subdir only RBC 20060203 
 
2519
            # log everything
 
2520
            # FIXME ? log the current subdir only RBC 20060203
1550
2521
            if revision is not None \
1551
2522
                    and len(revision) > 0 and revision[0].get_branch():
1552
2523
                location = revision[0].get_branch()
1554
2525
                location = '.'
1555
2526
            dir, relpath = bzrdir.BzrDir.open_containing(location)
1556
2527
            b = dir.open_branch()
1557
 
 
1558
 
        b.lock_read()
1559
 
        try:
1560
 
            if revision is None:
1561
 
                rev1 = None
1562
 
                rev2 = None
1563
 
            elif len(revision) == 1:
1564
 
                rev1 = rev2 = revision[0].in_history(b).revno
1565
 
            elif len(revision) == 2:
1566
 
                if revision[1].get_branch() != revision[0].get_branch():
1567
 
                    # b is taken from revision[0].get_branch(), and
1568
 
                    # show_log will use its revision_history. Having
1569
 
                    # different branches will lead to weird behaviors.
1570
 
                    raise errors.BzrCommandError(
1571
 
                        "Log doesn't accept two revisions in different"
1572
 
                        " branches.")
1573
 
                if revision[0].spec is None:
1574
 
                    # missing begin-range means first revision
1575
 
                    rev1 = 1
1576
 
                else:
1577
 
                    rev1 = revision[0].in_history(b).revno
1578
 
 
1579
 
                if revision[1].spec is None:
1580
 
                    # missing end-range means last known revision
1581
 
                    rev2 = b.revno()
1582
 
                else:
1583
 
                    rev2 = revision[1].in_history(b).revno
1584
 
            else:
1585
 
                raise errors.BzrCommandError(
1586
 
                    'bzr log --revision takes one or two values.')
1587
 
 
1588
 
            # By this point, the revision numbers are converted to the +ve
1589
 
            # form if they were supplied in the -ve form, so we can do
1590
 
            # this comparison in relative safety
1591
 
            if rev1 > rev2:
1592
 
                (rev2, rev1) = (rev1, rev2)
1593
 
 
1594
 
            if log_format is None:
1595
 
                log_format = log.log_formatter_registry.get_default(b)
1596
 
 
1597
 
            lf = log_format(show_ids=show_ids, to_file=self.outf,
1598
 
                            show_timezone=timezone)
1599
 
 
1600
 
            show_log(b,
1601
 
                     lf,
1602
 
                     file_id,
1603
 
                     verbose=verbose,
1604
 
                     direction=direction,
1605
 
                     start_revision=rev1,
1606
 
                     end_revision=rev2,
1607
 
                     search=message)
1608
 
        finally:
1609
 
            b.unlock()
1610
 
 
 
2528
            self.add_cleanup(b.lock_read().unlock)
 
2529
            rev1, rev2 = _get_revision_range(revision, b, self.name())
 
2530
 
 
2531
        if b.get_config().validate_signatures_in_log():
 
2532
            signatures = True
 
2533
 
 
2534
        if signatures:
 
2535
            if not gpg.GPGStrategy.verify_signatures_available():
 
2536
                raise errors.GpgmeNotInstalled(None)
 
2537
 
 
2538
        # Decide on the type of delta & diff filtering to use
 
2539
        # TODO: add an --all-files option to make this configurable & consistent
 
2540
        if not verbose:
 
2541
            delta_type = None
 
2542
        else:
 
2543
            delta_type = 'full'
 
2544
        if not show_diff:
 
2545
            diff_type = None
 
2546
        elif file_ids:
 
2547
            diff_type = 'partial'
 
2548
        else:
 
2549
            diff_type = 'full'
 
2550
 
 
2551
        # Build the log formatter
 
2552
        if log_format is None:
 
2553
            log_format = log.log_formatter_registry.get_default(b)
 
2554
        # Make a non-encoding output to include the diffs - bug 328007
 
2555
        unencoded_output = ui.ui_factory.make_output_stream(encoding_type='exact')
 
2556
        lf = log_format(show_ids=show_ids, to_file=self.outf,
 
2557
                        to_exact_file=unencoded_output,
 
2558
                        show_timezone=timezone,
 
2559
                        delta_format=get_verbosity_level(),
 
2560
                        levels=levels,
 
2561
                        show_advice=levels is None,
 
2562
                        author_list_handler=authors)
 
2563
 
 
2564
        # Choose the algorithm for doing the logging. It's annoying
 
2565
        # having multiple code paths like this but necessary until
 
2566
        # the underlying repository format is faster at generating
 
2567
        # deltas or can provide everything we need from the indices.
 
2568
        # The default algorithm - match-using-deltas - works for
 
2569
        # multiple files and directories and is faster for small
 
2570
        # amounts of history (200 revisions say). However, it's too
 
2571
        # slow for logging a single file in a repository with deep
 
2572
        # history, i.e. > 10K revisions. In the spirit of "do no
 
2573
        # evil when adding features", we continue to use the
 
2574
        # original algorithm - per-file-graph - for the "single
 
2575
        # file that isn't a directory without showing a delta" case.
 
2576
        partial_history = revision and b.repository._format.supports_chks
 
2577
        match_using_deltas = (len(file_ids) != 1 or filter_by_dir
 
2578
            or delta_type or partial_history)
 
2579
 
 
2580
        match_dict = {}
 
2581
        if match:
 
2582
            match_dict[''] = match
 
2583
        if match_message:
 
2584
            match_dict['message'] = match_message
 
2585
        if match_committer:
 
2586
            match_dict['committer'] = match_committer
 
2587
        if match_author:
 
2588
            match_dict['author'] = match_author
 
2589
        if match_bugs:
 
2590
            match_dict['bugs'] = match_bugs
 
2591
            
 
2592
        # Build the LogRequest and execute it
 
2593
        if len(file_ids) == 0:
 
2594
            file_ids = None
 
2595
        rqst = make_log_request_dict(
 
2596
            direction=direction, specific_fileids=file_ids,
 
2597
            start_revision=rev1, end_revision=rev2, limit=limit,
 
2598
            message_search=message, delta_type=delta_type,
 
2599
            diff_type=diff_type, _match_using_deltas=match_using_deltas,
 
2600
            exclude_common_ancestry=exclude_common_ancestry, match=match_dict,
 
2601
            signature=signatures
 
2602
            )
 
2603
        Logger(b, rqst).show(lf)
 
2604
 
 
2605
 
 
2606
def _get_revision_range(revisionspec_list, branch, command_name):
 
2607
    """Take the input of a revision option and turn it into a revision range.
 
2608
 
 
2609
    It returns RevisionInfo objects which can be used to obtain the rev_id's
 
2610
    of the desired revisions. It does some user input validations.
 
2611
    """
 
2612
    if revisionspec_list is None:
 
2613
        rev1 = None
 
2614
        rev2 = None
 
2615
    elif len(revisionspec_list) == 1:
 
2616
        rev1 = rev2 = revisionspec_list[0].in_history(branch)
 
2617
    elif len(revisionspec_list) == 2:
 
2618
        start_spec = revisionspec_list[0]
 
2619
        end_spec = revisionspec_list[1]
 
2620
        if end_spec.get_branch() != start_spec.get_branch():
 
2621
            # b is taken from revision[0].get_branch(), and
 
2622
            # show_log will use its revision_history. Having
 
2623
            # different branches will lead to weird behaviors.
 
2624
            raise errors.BzrCommandError(
 
2625
                "bzr %s doesn't accept two revisions in different"
 
2626
                " branches." % command_name)
 
2627
        if start_spec.spec is None:
 
2628
            # Avoid loading all the history.
 
2629
            rev1 = RevisionInfo(branch, None, None)
 
2630
        else:
 
2631
            rev1 = start_spec.in_history(branch)
 
2632
        # Avoid loading all of history when we know a missing
 
2633
        # end of range means the last revision ...
 
2634
        if end_spec.spec is None:
 
2635
            last_revno, last_revision_id = branch.last_revision_info()
 
2636
            rev2 = RevisionInfo(branch, last_revno, last_revision_id)
 
2637
        else:
 
2638
            rev2 = end_spec.in_history(branch)
 
2639
    else:
 
2640
        raise errors.BzrCommandError(
 
2641
            'bzr %s --revision takes one or two values.' % command_name)
 
2642
    return rev1, rev2
 
2643
 
 
2644
 
 
2645
def _revision_range_to_revid_range(revision_range):
 
2646
    rev_id1 = None
 
2647
    rev_id2 = None
 
2648
    if revision_range[0] is not None:
 
2649
        rev_id1 = revision_range[0].rev_id
 
2650
    if revision_range[1] is not None:
 
2651
        rev_id2 = revision_range[1].rev_id
 
2652
    return rev_id1, rev_id2
1611
2653
 
1612
2654
def get_log_format(long=False, short=False, line=False, default='long'):
1613
2655
    log_format = default
1621
2663
 
1622
2664
 
1623
2665
class cmd_touching_revisions(Command):
1624
 
    """Return revision-ids which affected a particular file.
 
2666
    __doc__ = """Return revision-ids which affected a particular file.
1625
2667
 
1626
2668
    A more user-friendly interface is "bzr log FILE".
1627
2669
    """
1632
2674
    @display_command
1633
2675
    def run(self, filename):
1634
2676
        tree, relpath = WorkingTree.open_containing(filename)
 
2677
        file_id = tree.path2id(relpath)
1635
2678
        b = tree.branch
1636
 
        inv = tree.read_working_inventory()
1637
 
        file_id = inv.path2id(relpath)
1638
 
        for revno, revision_id, what in log.find_touching_revisions(b, file_id):
 
2679
        self.add_cleanup(b.lock_read().unlock)
 
2680
        touching_revs = log.find_touching_revisions(b, file_id)
 
2681
        for revno, revision_id, what in touching_revs:
1639
2682
            self.outf.write("%6d %s\n" % (revno, what))
1640
2683
 
1641
2684
 
1642
2685
class cmd_ls(Command):
1643
 
    """List files in a tree.
 
2686
    __doc__ = """List files in a tree.
1644
2687
    """
1645
2688
 
 
2689
    _see_also = ['status', 'cat']
1646
2690
    takes_args = ['path?']
1647
 
    # TODO: Take a revision or remote path and list that tree instead.
1648
 
    takes_options = ['verbose', 'revision',
1649
 
                     Option('non-recursive',
1650
 
                            help='don\'t recurse into sub-directories'),
1651
 
                     Option('from-root',
1652
 
                            help='Print all paths from the root of the branch.'),
1653
 
                     Option('unknown', help='Print unknown files'),
1654
 
                     Option('versioned', help='Print versioned files'),
1655
 
                     Option('ignored', help='Print ignored files'),
1656
 
 
1657
 
                     Option('null', help='Null separate the files'),
1658
 
                     'kind', 'show-ids'
1659
 
                    ]
 
2691
    takes_options = [
 
2692
            'verbose',
 
2693
            'revision',
 
2694
            Option('recursive', short_name='R',
 
2695
                   help='Recurse into subdirectories.'),
 
2696
            Option('from-root',
 
2697
                   help='Print paths relative to the root of the branch.'),
 
2698
            Option('unknown', short_name='u',
 
2699
                help='Print unknown files.'),
 
2700
            Option('versioned', help='Print versioned files.',
 
2701
                   short_name='V'),
 
2702
            Option('ignored', short_name='i',
 
2703
                help='Print ignored files.'),
 
2704
            Option('kind', short_name='k',
 
2705
                   help='List entries of a particular kind: file, directory, symlink.',
 
2706
                   type=unicode),
 
2707
            'null',
 
2708
            'show-ids',
 
2709
            'directory',
 
2710
            ]
1660
2711
    @display_command
1661
 
    def run(self, revision=None, verbose=False, 
1662
 
            non_recursive=False, from_root=False,
 
2712
    def run(self, revision=None, verbose=False,
 
2713
            recursive=False, from_root=False,
1663
2714
            unknown=False, versioned=False, ignored=False,
1664
 
            null=False, kind=None, show_ids=False, path=None):
 
2715
            null=False, kind=None, show_ids=False, path=None, directory=None):
1665
2716
 
1666
2717
        if kind and kind not in ('file', 'directory', 'symlink'):
1667
2718
            raise errors.BzrCommandError('invalid kind specified')
1674
2725
 
1675
2726
        if path is None:
1676
2727
            fs_path = '.'
1677
 
            prefix = ''
1678
2728
        else:
1679
2729
            if from_root:
1680
2730
                raise errors.BzrCommandError('cannot specify both --from-root'
1681
2731
                                             ' and PATH')
1682
2732
            fs_path = path
1683
 
            prefix = path
1684
 
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
1685
 
            fs_path)
 
2733
        tree, branch, relpath = \
 
2734
            _open_directory_or_containing_tree_or_branch(fs_path, directory)
 
2735
 
 
2736
        # Calculate the prefix to use
 
2737
        prefix = None
1686
2738
        if from_root:
1687
 
            relpath = u''
1688
 
        elif relpath:
1689
 
            relpath += '/'
1690
 
        if revision is not None:
1691
 
            tree = branch.repository.revision_tree(
1692
 
                revision[0].in_history(branch).rev_id)
1693
 
        elif tree is None:
1694
 
            tree = branch.basis_tree()
1695
 
 
1696
 
        tree.lock_read()
1697
 
        try:
1698
 
            for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
1699
 
                if fp.startswith(relpath):
1700
 
                    fp = osutils.pathjoin(prefix, fp[len(relpath):])
1701
 
                    if non_recursive and '/' in fp:
1702
 
                        continue
1703
 
                    if not all and not selection[fc]:
1704
 
                        continue
1705
 
                    if kind is not None and fkind != kind:
1706
 
                        continue
1707
 
                    if verbose:
1708
 
                        kindch = entry.kind_character()
1709
 
                        outstring = '%-8s %s%s' % (fc, fp, kindch)
1710
 
                        if show_ids and fid is not None:
1711
 
                            outstring = "%-50s %s" % (outstring, fid)
1712
 
                        self.outf.write(outstring + '\n')
1713
 
                    elif null:
1714
 
                        self.outf.write(fp + '\0')
1715
 
                        if show_ids:
1716
 
                            if fid is not None:
1717
 
                                self.outf.write(fid)
1718
 
                            self.outf.write('\0')
1719
 
                        self.outf.flush()
1720
 
                    else:
1721
 
                        if fid is not None:
1722
 
                            my_id = fid
1723
 
                        else:
1724
 
                            my_id = ''
1725
 
                        if show_ids:
1726
 
                            self.outf.write('%-50s %s\n' % (fp, my_id))
1727
 
                        else:
1728
 
                            self.outf.write(fp + '\n')
1729
 
        finally:
1730
 
            tree.unlock()
 
2739
            if relpath:
 
2740
                prefix = relpath + '/'
 
2741
        elif fs_path != '.' and not fs_path.endswith('/'):
 
2742
            prefix = fs_path + '/'
 
2743
 
 
2744
        if revision is not None or tree is None:
 
2745
            tree = _get_one_revision_tree('ls', revision, branch=branch)
 
2746
 
 
2747
        apply_view = False
 
2748
        if isinstance(tree, WorkingTree) and tree.supports_views():
 
2749
            view_files = tree.views.lookup_view()
 
2750
            if view_files:
 
2751
                apply_view = True
 
2752
                view_str = views.view_display_str(view_files)
 
2753
                note("Ignoring files outside view. View is %s" % view_str)
 
2754
 
 
2755
        self.add_cleanup(tree.lock_read().unlock)
 
2756
        for fp, fc, fkind, fid, entry in tree.list_files(include_root=False,
 
2757
            from_dir=relpath, recursive=recursive):
 
2758
            # Apply additional masking
 
2759
            if not all and not selection[fc]:
 
2760
                continue
 
2761
            if kind is not None and fkind != kind:
 
2762
                continue
 
2763
            if apply_view:
 
2764
                try:
 
2765
                    if relpath:
 
2766
                        fullpath = osutils.pathjoin(relpath, fp)
 
2767
                    else:
 
2768
                        fullpath = fp
 
2769
                    views.check_path_in_view(tree, fullpath)
 
2770
                except errors.FileOutsideView:
 
2771
                    continue
 
2772
 
 
2773
            # Output the entry
 
2774
            if prefix:
 
2775
                fp = osutils.pathjoin(prefix, fp)
 
2776
            kindch = entry.kind_character()
 
2777
            outstring = fp + kindch
 
2778
            ui.ui_factory.clear_term()
 
2779
            if verbose:
 
2780
                outstring = '%-8s %s' % (fc, outstring)
 
2781
                if show_ids and fid is not None:
 
2782
                    outstring = "%-50s %s" % (outstring, fid)
 
2783
                self.outf.write(outstring + '\n')
 
2784
            elif null:
 
2785
                self.outf.write(fp + '\0')
 
2786
                if show_ids:
 
2787
                    if fid is not None:
 
2788
                        self.outf.write(fid)
 
2789
                    self.outf.write('\0')
 
2790
                self.outf.flush()
 
2791
            else:
 
2792
                if show_ids:
 
2793
                    if fid is not None:
 
2794
                        my_id = fid
 
2795
                    else:
 
2796
                        my_id = ''
 
2797
                    self.outf.write('%-50s %s\n' % (outstring, my_id))
 
2798
                else:
 
2799
                    self.outf.write(outstring + '\n')
1731
2800
 
1732
2801
 
1733
2802
class cmd_unknowns(Command):
1734
 
    """List unknown files.
1735
 
 
1736
 
    See also: "bzr ls --unknown".
 
2803
    __doc__ = """List unknown files.
1737
2804
    """
1738
2805
 
1739
2806
    hidden = True
 
2807
    _see_also = ['ls']
 
2808
    takes_options = ['directory']
1740
2809
 
1741
2810
    @display_command
1742
 
    def run(self):
1743
 
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
 
2811
    def run(self, directory=u'.'):
 
2812
        for f in WorkingTree.open_containing(directory)[0].unknowns():
1744
2813
            self.outf.write(osutils.quotefn(f) + '\n')
1745
2814
 
1746
2815
 
1747
2816
class cmd_ignore(Command):
1748
 
    """Ignore specified files or patterns.
 
2817
    __doc__ = """Ignore specified files or patterns.
 
2818
 
 
2819
    See ``bzr help patterns`` for details on the syntax of patterns.
 
2820
 
 
2821
    If a .bzrignore file does not exist, the ignore command
 
2822
    will create one and add the specified files or patterns to the newly
 
2823
    created file. The ignore command will also automatically add the 
 
2824
    .bzrignore file to be versioned. Creating a .bzrignore file without
 
2825
    the use of the ignore command will require an explicit add command.
1749
2826
 
1750
2827
    To remove patterns from the ignore list, edit the .bzrignore file.
1751
 
 
1752
 
    Trailing slashes on patterns are ignored. 
1753
 
    If the pattern contains a slash or is a regular expression, it is compared 
1754
 
    to the whole path from the branch root.  Otherwise, it is compared to only
1755
 
    the last component of the path.  To match a file only in the root 
1756
 
    directory, prepend './'.
1757
 
 
1758
 
    Ignore patterns specifying absolute paths are not allowed.
1759
 
 
1760
 
    Ignore patterns may include globbing wildcards such as:
1761
 
      ? - Matches any single character except '/'
1762
 
      * - Matches 0 or more characters except '/'
1763
 
      /**/ - Matches 0 or more directories in a path
1764
 
      [a-z] - Matches a single character from within a group of characters
1765
 
 
1766
 
    Ignore patterns may also be Python regular expressions.  
1767
 
    Regular expression ignore patterns are identified by a 'RE:' prefix 
1768
 
    followed by the regular expression.  Regular expression ignore patterns
1769
 
    may not include named or numbered groups.
1770
 
 
1771
 
    Note: ignore patterns containing shell wildcards must be quoted from 
1772
 
    the shell on Unix.
1773
 
 
1774
 
    examples:
1775
 
        bzr ignore ./Makefile
1776
 
        bzr ignore '*.class'
1777
 
        bzr ignore 'lib/**/*.o'
1778
 
        bzr ignore 'RE:lib/.*\.o'
 
2828
    After adding, editing or deleting that file either indirectly by
 
2829
    using this command or directly by using an editor, be sure to commit
 
2830
    it.
 
2831
    
 
2832
    Bazaar also supports a global ignore file ~/.bazaar/ignore. On Windows
 
2833
    the global ignore file can be found in the application data directory as
 
2834
    C:\\Documents and Settings\\<user>\\Application Data\\Bazaar\\2.0\\ignore.
 
2835
    Global ignores are not touched by this command. The global ignore file
 
2836
    can be edited directly using an editor.
 
2837
 
 
2838
    Patterns prefixed with '!' are exceptions to ignore patterns and take
 
2839
    precedence over regular ignores.  Such exceptions are used to specify
 
2840
    files that should be versioned which would otherwise be ignored.
 
2841
    
 
2842
    Patterns prefixed with '!!' act as regular ignore patterns, but have
 
2843
    precedence over the '!' exception patterns.
 
2844
 
 
2845
    :Notes: 
 
2846
        
 
2847
    * Ignore patterns containing shell wildcards must be quoted from
 
2848
      the shell on Unix.
 
2849
 
 
2850
    * Ignore patterns starting with "#" act as comments in the ignore file.
 
2851
      To ignore patterns that begin with that character, use the "RE:" prefix.
 
2852
 
 
2853
    :Examples:
 
2854
        Ignore the top level Makefile::
 
2855
 
 
2856
            bzr ignore ./Makefile
 
2857
 
 
2858
        Ignore .class files in all directories...::
 
2859
 
 
2860
            bzr ignore "*.class"
 
2861
 
 
2862
        ...but do not ignore "special.class"::
 
2863
 
 
2864
            bzr ignore "!special.class"
 
2865
 
 
2866
        Ignore files whose name begins with the "#" character::
 
2867
 
 
2868
            bzr ignore "RE:^#"
 
2869
 
 
2870
        Ignore .o files under the lib directory::
 
2871
 
 
2872
            bzr ignore "lib/**/*.o"
 
2873
 
 
2874
        Ignore .o files under the lib directory::
 
2875
 
 
2876
            bzr ignore "RE:lib/.*\.o"
 
2877
 
 
2878
        Ignore everything but the "debian" toplevel directory::
 
2879
 
 
2880
            bzr ignore "RE:(?!debian/).*"
 
2881
        
 
2882
        Ignore everything except the "local" toplevel directory,
 
2883
        but always ignore autosave files ending in ~, even under local/::
 
2884
        
 
2885
            bzr ignore "*"
 
2886
            bzr ignore "!./local"
 
2887
            bzr ignore "!!*~"
1779
2888
    """
 
2889
 
 
2890
    _see_also = ['status', 'ignored', 'patterns']
1780
2891
    takes_args = ['name_pattern*']
1781
 
    takes_options = [
1782
 
                     Option('old-default-rules',
1783
 
                            help='Out the ignore rules bzr < 0.9 always used.')
1784
 
                     ]
1785
 
    
1786
 
    def run(self, name_pattern_list=None, old_default_rules=None):
1787
 
        from bzrlib.atomicfile import AtomicFile
1788
 
        if old_default_rules is not None:
1789
 
            # dump the rules and exit
1790
 
            for pattern in ignores.OLD_DEFAULTS:
1791
 
                print pattern
 
2892
    takes_options = ['directory',
 
2893
        Option('default-rules',
 
2894
               help='Display the default ignore rules that bzr uses.')
 
2895
        ]
 
2896
 
 
2897
    def run(self, name_pattern_list=None, default_rules=None,
 
2898
            directory=u'.'):
 
2899
        from bzrlib import ignores
 
2900
        if default_rules is not None:
 
2901
            # dump the default rules and exit
 
2902
            for pattern in ignores.USER_DEFAULTS:
 
2903
                self.outf.write("%s\n" % pattern)
1792
2904
            return
1793
2905
        if not name_pattern_list:
1794
2906
            raise errors.BzrCommandError("ignore requires at least one "
1795
 
                                  "NAME_PATTERN or --old-default-rules")
 
2907
                "NAME_PATTERN or --default-rules.")
 
2908
        name_pattern_list = [globbing.normalize_pattern(p)
 
2909
                             for p in name_pattern_list]
 
2910
        bad_patterns = ''
 
2911
        for p in name_pattern_list:
 
2912
            if not globbing.Globster.is_pattern_valid(p):
 
2913
                bad_patterns += ('\n  %s' % p)
 
2914
        if bad_patterns:
 
2915
            msg = ('Invalid ignore pattern(s) found. %s' % bad_patterns)
 
2916
            ui.ui_factory.show_error(msg)
 
2917
            raise errors.InvalidPattern('')
1796
2918
        for name_pattern in name_pattern_list:
1797
 
            if name_pattern[0] == '/':
 
2919
            if (name_pattern[0] == '/' or
 
2920
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
1798
2921
                raise errors.BzrCommandError(
1799
2922
                    "NAME_PATTERN should not be an absolute path")
1800
 
        tree, relpath = WorkingTree.open_containing(u'.')
1801
 
        ifn = tree.abspath('.bzrignore')
1802
 
        if os.path.exists(ifn):
1803
 
            f = open(ifn, 'rt')
1804
 
            try:
1805
 
                igns = f.read().decode('utf-8')
1806
 
            finally:
1807
 
                f.close()
1808
 
        else:
1809
 
            igns = ''
1810
 
 
1811
 
        # TODO: If the file already uses crlf-style termination, maybe
1812
 
        # we should use that for the newly added lines?
1813
 
 
1814
 
        if igns and igns[-1] != '\n':
1815
 
            igns += '\n'
1816
 
        for name_pattern in name_pattern_list:
1817
 
            igns += name_pattern.rstrip('/') + '\n'
1818
 
 
1819
 
        f = AtomicFile(ifn, 'wb')
1820
 
        try:
1821
 
            f.write(igns.encode('utf-8'))
1822
 
            f.commit()
1823
 
        finally:
1824
 
            f.close()
1825
 
 
1826
 
        inv = tree.inventory
1827
 
        if inv.path2id('.bzrignore'):
1828
 
            mutter('.bzrignore is already versioned')
1829
 
        else:
1830
 
            mutter('need to make new .bzrignore file versioned')
1831
 
            tree.add(['.bzrignore'])
 
2923
        tree, relpath = WorkingTree.open_containing(directory)
 
2924
        ignores.tree_ignores_add_patterns(tree, name_pattern_list)
 
2925
        ignored = globbing.Globster(name_pattern_list)
 
2926
        matches = []
 
2927
        self.add_cleanup(tree.lock_read().unlock)
 
2928
        for entry in tree.list_files():
 
2929
            id = entry[3]
 
2930
            if id is not None:
 
2931
                filename = entry[0]
 
2932
                if ignored.match(filename):
 
2933
                    matches.append(filename)
 
2934
        if len(matches) > 0:
 
2935
            self.outf.write("Warning: the following files are version controlled and"
 
2936
                  " match your ignore pattern:\n%s"
 
2937
                  "\nThese files will continue to be version controlled"
 
2938
                  " unless you 'bzr remove' them.\n" % ("\n".join(matches),))
1832
2939
 
1833
2940
 
1834
2941
class cmd_ignored(Command):
1835
 
    """List ignored files and the patterns that matched them.
1836
 
 
1837
 
    See also: bzr ignore"""
 
2942
    __doc__ = """List ignored files and the patterns that matched them.
 
2943
 
 
2944
    List all the ignored files and the ignore pattern that caused the file to
 
2945
    be ignored.
 
2946
 
 
2947
    Alternatively, to list just the files::
 
2948
 
 
2949
        bzr ls --ignored
 
2950
    """
 
2951
 
 
2952
    encoding_type = 'replace'
 
2953
    _see_also = ['ignore', 'ls']
 
2954
    takes_options = ['directory']
 
2955
 
1838
2956
    @display_command
1839
 
    def run(self):
1840
 
        tree = WorkingTree.open_containing(u'.')[0]
1841
 
        tree.lock_read()
1842
 
        try:
1843
 
            for path, file_class, kind, file_id, entry in tree.list_files():
1844
 
                if file_class != 'I':
1845
 
                    continue
1846
 
                ## XXX: Slightly inefficient since this was already calculated
1847
 
                pat = tree.is_ignored(path)
1848
 
                print '%-50s %s' % (path, pat)
1849
 
        finally:
1850
 
            tree.unlock()
 
2957
    def run(self, directory=u'.'):
 
2958
        tree = WorkingTree.open_containing(directory)[0]
 
2959
        self.add_cleanup(tree.lock_read().unlock)
 
2960
        for path, file_class, kind, file_id, entry in tree.list_files():
 
2961
            if file_class != 'I':
 
2962
                continue
 
2963
            ## XXX: Slightly inefficient since this was already calculated
 
2964
            pat = tree.is_ignored(path)
 
2965
            self.outf.write('%-50s %s\n' % (path, pat))
1851
2966
 
1852
2967
 
1853
2968
class cmd_lookup_revision(Command):
1854
 
    """Lookup the revision-id from a revision-number
 
2969
    __doc__ = """Lookup the revision-id from a revision-number
1855
2970
 
1856
 
    example:
 
2971
    :Examples:
1857
2972
        bzr lookup-revision 33
1858
2973
    """
1859
2974
    hidden = True
1860
2975
    takes_args = ['revno']
1861
 
    
 
2976
    takes_options = ['directory']
 
2977
 
1862
2978
    @display_command
1863
 
    def run(self, revno):
 
2979
    def run(self, revno, directory=u'.'):
1864
2980
        try:
1865
2981
            revno = int(revno)
1866
2982
        except ValueError:
1867
 
            raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
1868
 
 
1869
 
        print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
 
2983
            raise errors.BzrCommandError("not a valid revision-number: %r"
 
2984
                                         % revno)
 
2985
        revid = WorkingTree.open_containing(directory)[0].branch.get_rev_id(revno)
 
2986
        self.outf.write("%s\n" % revid)
1870
2987
 
1871
2988
 
1872
2989
class cmd_export(Command):
1873
 
    """Export past revision to destination directory.
 
2990
    __doc__ = """Export current or past revision to a destination directory or archive.
1874
2991
 
1875
2992
    If no revision is specified this exports the last committed revision.
1876
2993
 
1878
2995
    given, try to find the format with the extension. If no extension
1879
2996
    is found exports to a directory (equivalent to --format=dir).
1880
2997
 
1881
 
    Root may be the top directory for tar, tgz and tbz2 formats. If none
1882
 
    is given, the top directory will be the root name of the file.
1883
 
 
1884
 
    If branch is omitted then the branch containing the CWD will be used.
1885
 
 
1886
 
    Note: export of tree with non-ascii filenames to zip is not supported.
1887
 
 
1888
 
     Supported formats       Autodetected by extension
1889
 
     -----------------       -------------------------
1890
 
         dir                            -
 
2998
    If root is supplied, it will be used as the root directory inside
 
2999
    container formats (tar, zip, etc). If it is not supplied it will default
 
3000
    to the exported filename. The root option has no effect for 'dir' format.
 
3001
 
 
3002
    If branch is omitted then the branch containing the current working
 
3003
    directory will be used.
 
3004
 
 
3005
    Note: Export of tree with non-ASCII filenames to zip is not supported.
 
3006
 
 
3007
      =================       =========================
 
3008
      Supported formats       Autodetected by extension
 
3009
      =================       =========================
 
3010
         dir                         (none)
1891
3011
         tar                          .tar
1892
3012
         tbz2                    .tar.bz2, .tbz2
1893
3013
         tgz                      .tar.gz, .tgz
1894
3014
         zip                          .zip
 
3015
      =================       =========================
1895
3016
    """
1896
 
    takes_args = ['dest', 'branch?']
1897
 
    takes_options = ['revision', 'format', 'root']
1898
 
    def run(self, dest, branch=None, revision=None, format=None, root=None):
 
3017
    encoding = 'exact'
 
3018
    takes_args = ['dest', 'branch_or_subdir?']
 
3019
    takes_options = ['directory',
 
3020
        Option('format',
 
3021
               help="Type of file to export to.",
 
3022
               type=unicode),
 
3023
        'revision',
 
3024
        Option('filters', help='Apply content filters to export the '
 
3025
                'convenient form.'),
 
3026
        Option('root',
 
3027
               type=str,
 
3028
               help="Name of the root directory inside the exported file."),
 
3029
        Option('per-file-timestamps',
 
3030
               help='Set modification time of files to that of the last '
 
3031
                    'revision in which it was changed.'),
 
3032
        ]
 
3033
    def run(self, dest, branch_or_subdir=None, revision=None, format=None,
 
3034
        root=None, filters=False, per_file_timestamps=False, directory=u'.'):
1899
3035
        from bzrlib.export import export
1900
3036
 
1901
 
        if branch is None:
1902
 
            tree = WorkingTree.open_containing(u'.')[0]
 
3037
        if branch_or_subdir is None:
 
3038
            tree = WorkingTree.open_containing(directory)[0]
1903
3039
            b = tree.branch
1904
 
        else:
1905
 
            b = Branch.open(branch)
1906
 
            
1907
 
        if revision is None:
1908
 
            # should be tree.last_revision  FIXME
1909
 
            rev_id = b.last_revision()
1910
 
        else:
1911
 
            if len(revision) != 1:
1912
 
                raise errors.BzrCommandError('bzr export --revision takes exactly 1 argument')
1913
 
            rev_id = revision[0].in_history(b).rev_id
1914
 
        t = b.repository.revision_tree(rev_id)
 
3040
            subdir = None
 
3041
        else:
 
3042
            b, subdir = Branch.open_containing(branch_or_subdir)
 
3043
            tree = None
 
3044
 
 
3045
        rev_tree = _get_one_revision_tree('export', revision, branch=b, tree=tree)
1915
3046
        try:
1916
 
            export(t, dest, format, root)
 
3047
            export(rev_tree, dest, format, root, subdir, filtered=filters,
 
3048
                   per_file_timestamps=per_file_timestamps)
1917
3049
        except errors.NoSuchExportFormat, e:
1918
3050
            raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
1919
3051
 
1920
3052
 
1921
3053
class cmd_cat(Command):
1922
 
    """Write a file's text from a previous revision."""
1923
 
 
1924
 
    takes_options = ['revision', 'name-from-revision']
 
3054
    __doc__ = """Write the contents of a file as of a given revision to standard output.
 
3055
 
 
3056
    If no revision is nominated, the last revision is used.
 
3057
 
 
3058
    Note: Take care to redirect standard output when using this command on a
 
3059
    binary file.
 
3060
    """
 
3061
 
 
3062
    _see_also = ['ls']
 
3063
    takes_options = ['directory',
 
3064
        Option('name-from-revision', help='The path name in the old tree.'),
 
3065
        Option('filters', help='Apply content filters to display the '
 
3066
                'convenience form.'),
 
3067
        'revision',
 
3068
        ]
1925
3069
    takes_args = ['filename']
1926
3070
    encoding_type = 'exact'
1927
3071
 
1928
3072
    @display_command
1929
 
    def run(self, filename, revision=None, name_from_revision=False):
 
3073
    def run(self, filename, revision=None, name_from_revision=False,
 
3074
            filters=False, directory=None):
1930
3075
        if revision is not None and len(revision) != 1:
1931
3076
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
1932
 
                                        " one number")
1933
 
 
1934
 
        tree = None
1935
 
        try:
1936
 
            tree, relpath = WorkingTree.open_containing(filename)
1937
 
            b = tree.branch
1938
 
        except (errors.NotBranchError, errors.NotLocalUrl):
1939
 
            pass
1940
 
 
1941
 
        if revision is not None and revision[0].get_branch() is not None:
1942
 
            b = Branch.open(revision[0].get_branch())
 
3077
                                         " one revision specifier")
 
3078
        tree, branch, relpath = \
 
3079
            _open_directory_or_containing_tree_or_branch(filename, directory)
 
3080
        self.add_cleanup(branch.lock_read().unlock)
 
3081
        return self._run(tree, branch, relpath, filename, revision,
 
3082
                         name_from_revision, filters)
 
3083
 
 
3084
    def _run(self, tree, b, relpath, filename, revision, name_from_revision,
 
3085
        filtered):
1943
3086
        if tree is None:
1944
 
            b, relpath = Branch.open_containing(filename)
1945
3087
            tree = b.basis_tree()
1946
 
        if revision is None:
1947
 
            revision_id = b.last_revision()
1948
 
        else:
1949
 
            revision_id = revision[0].in_history(b).rev_id
 
3088
        rev_tree = _get_one_revision_tree('cat', revision, branch=b)
 
3089
        self.add_cleanup(rev_tree.lock_read().unlock)
1950
3090
 
1951
 
        cur_file_id = tree.path2id(relpath)
1952
 
        rev_tree = b.repository.revision_tree(revision_id)
1953
3091
        old_file_id = rev_tree.path2id(relpath)
1954
 
        
 
3092
 
 
3093
        # TODO: Split out this code to something that generically finds the
 
3094
        # best id for a path across one or more trees; it's like
 
3095
        # find_ids_across_trees but restricted to find just one. -- mbp
 
3096
        # 20110705.
1955
3097
        if name_from_revision:
 
3098
            # Try in revision if requested
1956
3099
            if old_file_id is None:
1957
 
                raise errors.BzrCommandError("%r is not present in revision %s"
1958
 
                                                % (filename, revision_id))
1959
 
            else:
1960
 
                rev_tree.print_file(old_file_id)
1961
 
        elif cur_file_id is not None:
1962
 
            rev_tree.print_file(cur_file_id)
1963
 
        elif old_file_id is not None:
1964
 
            rev_tree.print_file(old_file_id)
1965
 
        else:
1966
 
            raise errors.BzrCommandError("%r is not present in revision %s" %
1967
 
                                         (filename, revision_id))
 
3100
                raise errors.BzrCommandError(
 
3101
                    "%r is not present in revision %s" % (
 
3102
                        filename, rev_tree.get_revision_id()))
 
3103
            else:
 
3104
                actual_file_id = old_file_id
 
3105
        else:
 
3106
            cur_file_id = tree.path2id(relpath)
 
3107
            if cur_file_id is not None and rev_tree.has_id(cur_file_id):
 
3108
                actual_file_id = cur_file_id
 
3109
            elif old_file_id is not None:
 
3110
                actual_file_id = old_file_id
 
3111
            else:
 
3112
                raise errors.BzrCommandError(
 
3113
                    "%r is not present in revision %s" % (
 
3114
                        filename, rev_tree.get_revision_id()))
 
3115
        if filtered:
 
3116
            from bzrlib.filter_tree import ContentFilterTree
 
3117
            filter_tree = ContentFilterTree(rev_tree,
 
3118
                rev_tree._content_filter_stack)
 
3119
            content = filter_tree.get_file_text(actual_file_id)
 
3120
        else:
 
3121
            content = rev_tree.get_file_text(actual_file_id)
 
3122
        self.cleanup_now()
 
3123
        self.outf.write(content)
1968
3124
 
1969
3125
 
1970
3126
class cmd_local_time_offset(Command):
1971
 
    """Show the offset in seconds from GMT to local time."""
1972
 
    hidden = True    
 
3127
    __doc__ = """Show the offset in seconds from GMT to local time."""
 
3128
    hidden = True
1973
3129
    @display_command
1974
3130
    def run(self):
1975
 
        print osutils.local_time_offset()
 
3131
        self.outf.write("%s\n" % osutils.local_time_offset())
1976
3132
 
1977
3133
 
1978
3134
 
1979
3135
class cmd_commit(Command):
1980
 
    """Commit changes into a new revision.
1981
 
    
1982
 
    If no arguments are given, the entire tree is committed.
1983
 
 
1984
 
    If selected files are specified, only changes to those files are
1985
 
    committed.  If a directory is specified then the directory and everything 
1986
 
    within it is committed.
1987
 
 
1988
 
    A selected-file commit may fail in some cases where the committed
1989
 
    tree would be invalid, such as trying to commit a file in a
1990
 
    newly-added directory that is not itself committed.
 
3136
    __doc__ = """Commit changes into a new revision.
 
3137
 
 
3138
    An explanatory message needs to be given for each commit. This is
 
3139
    often done by using the --message option (getting the message from the
 
3140
    command line) or by using the --file option (getting the message from
 
3141
    a file). If neither of these options is given, an editor is opened for
 
3142
    the user to enter the message. To see the changed files in the
 
3143
    boilerplate text loaded into the editor, use the --show-diff option.
 
3144
 
 
3145
    By default, the entire tree is committed and the person doing the
 
3146
    commit is assumed to be the author. These defaults can be overridden
 
3147
    as explained below.
 
3148
 
 
3149
    :Selective commits:
 
3150
 
 
3151
      If selected files are specified, only changes to those files are
 
3152
      committed.  If a directory is specified then the directory and
 
3153
      everything within it is committed.
 
3154
  
 
3155
      When excludes are given, they take precedence over selected files.
 
3156
      For example, to commit only changes within foo, but not changes
 
3157
      within foo/bar::
 
3158
  
 
3159
        bzr commit foo -x foo/bar
 
3160
  
 
3161
      A selective commit after a merge is not yet supported.
 
3162
 
 
3163
    :Custom authors:
 
3164
 
 
3165
      If the author of the change is not the same person as the committer,
 
3166
      you can specify the author's name using the --author option. The
 
3167
      name should be in the same format as a committer-id, e.g.
 
3168
      "John Doe <jdoe@example.com>". If there is more than one author of
 
3169
      the change you can specify the option multiple times, once for each
 
3170
      author.
 
3171
  
 
3172
    :Checks:
 
3173
 
 
3174
      A common mistake is to forget to add a new file or directory before
 
3175
      running the commit command. The --strict option checks for unknown
 
3176
      files and aborts the commit if any are found. More advanced pre-commit
 
3177
      checks can be implemented by defining hooks. See ``bzr help hooks``
 
3178
      for details.
 
3179
 
 
3180
    :Things to note:
 
3181
 
 
3182
      If you accidentially commit the wrong changes or make a spelling
 
3183
      mistake in the commit message say, you can use the uncommit command
 
3184
      to undo it. See ``bzr help uncommit`` for details.
 
3185
 
 
3186
      Hooks can also be configured to run after a commit. This allows you
 
3187
      to trigger updates to external systems like bug trackers. The --fixes
 
3188
      option can be used to record the association between a revision and
 
3189
      one or more bugs. See ``bzr help bugs`` for details.
1991
3190
    """
1992
 
    # TODO: Run hooks on tree to-be-committed, and after commit.
1993
 
 
1994
 
    # TODO: Strict commit that fails if there are deleted files.
1995
 
    #       (what does "deleted files" mean ??)
1996
 
 
1997
 
    # TODO: Give better message for -s, --summary, used by tla people
1998
 
 
1999
 
    # XXX: verbose currently does nothing
2000
 
 
 
3191
 
 
3192
    _see_also = ['add', 'bugs', 'hooks', 'uncommit']
2001
3193
    takes_args = ['selected*']
2002
 
    takes_options = ['message', 'verbose', 
2003
 
                     Option('unchanged',
2004
 
                            help='commit even if nothing has changed'),
2005
 
                     Option('file', type=str, 
2006
 
                            short_name='F',
2007
 
                            argname='msgfile',
2008
 
                            help='file containing commit message'),
2009
 
                     Option('strict',
2010
 
                            help="refuse to commit if there are unknown "
2011
 
                            "files in the working tree."),
2012
 
                     Option('local',
2013
 
                            help="perform a local only commit in a bound "
2014
 
                                 "branch. Such commits are not pushed to "
2015
 
                                 "the master branch until a normal commit "
2016
 
                                 "is performed."
2017
 
                            ),
2018
 
                     ]
 
3194
    takes_options = [
 
3195
            ListOption('exclude', type=str, short_name='x',
 
3196
                help="Do not consider changes made to a given path."),
 
3197
            Option('message', type=unicode,
 
3198
                   short_name='m',
 
3199
                   help="Description of the new revision."),
 
3200
            'verbose',
 
3201
             Option('unchanged',
 
3202
                    help='Commit even if nothing has changed.'),
 
3203
             Option('file', type=str,
 
3204
                    short_name='F',
 
3205
                    argname='msgfile',
 
3206
                    help='Take commit message from this file.'),
 
3207
             Option('strict',
 
3208
                    help="Refuse to commit if there are unknown "
 
3209
                    "files in the working tree."),
 
3210
             Option('commit-time', type=str,
 
3211
                    help="Manually set a commit time using commit date "
 
3212
                    "format, e.g. '2009-10-10 08:00:00 +0100'."),
 
3213
             ListOption('fixes', type=str,
 
3214
                    help="Mark a bug as being fixed by this revision "
 
3215
                         "(see \"bzr help bugs\")."),
 
3216
             ListOption('author', type=unicode,
 
3217
                    help="Set the author's name, if it's different "
 
3218
                         "from the committer."),
 
3219
             Option('local',
 
3220
                    help="Perform a local commit in a bound "
 
3221
                         "branch.  Local commits are not pushed to "
 
3222
                         "the master branch until a normal commit "
 
3223
                         "is performed."
 
3224
                    ),
 
3225
             Option('show-diff', short_name='p',
 
3226
                    help='When no message is supplied, show the diff along'
 
3227
                    ' with the status summary in the message editor.'),
 
3228
             Option('lossy', 
 
3229
                    help='When committing to a foreign version control '
 
3230
                    'system do not push data that can not be natively '
 
3231
                    'represented.'),
 
3232
             ]
2019
3233
    aliases = ['ci', 'checkin']
2020
3234
 
2021
 
    def run(self, message=None, file=None, verbose=True, selected_list=None,
2022
 
            unchanged=False, strict=False, local=False):
2023
 
        from bzrlib.commit import (NullCommitReporter, ReportCommitToLog)
2024
 
        from bzrlib.errors import (PointlessCommit, ConflictsInTree,
2025
 
                StrictCommitFailed)
2026
 
        from bzrlib.msgeditor import edit_commit_message, \
2027
 
                make_commit_message_template
2028
 
 
2029
 
        # TODO: Need a blackbox test for invoking the external editor; may be
2030
 
        # slightly problematic to run this cross-platform.
2031
 
 
2032
 
        # TODO: do more checks that the commit will succeed before 
2033
 
        # spending the user's valuable time typing a commit message.
2034
 
        tree, selected_list = tree_files(selected_list)
 
3235
    def _iter_bug_fix_urls(self, fixes, branch):
 
3236
        # Configure the properties for bug fixing attributes.
 
3237
        for fixed_bug in fixes:
 
3238
            tokens = fixed_bug.split(':')
 
3239
            if len(tokens) != 2:
 
3240
                raise errors.BzrCommandError(
 
3241
                    "Invalid bug %s. Must be in the form of 'tracker:id'. "
 
3242
                    "See \"bzr help bugs\" for more information on this "
 
3243
                    "feature.\nCommit refused." % fixed_bug)
 
3244
            tag, bug_id = tokens
 
3245
            try:
 
3246
                yield bugtracker.get_bug_url(tag, branch, bug_id)
 
3247
            except errors.UnknownBugTrackerAbbreviation:
 
3248
                raise errors.BzrCommandError(
 
3249
                    'Unrecognized bug %s. Commit refused.' % fixed_bug)
 
3250
            except errors.MalformedBugIdentifier, e:
 
3251
                raise errors.BzrCommandError(
 
3252
                    "%s\nCommit refused." % (str(e),))
 
3253
 
 
3254
    def run(self, message=None, file=None, verbose=False, selected_list=None,
 
3255
            unchanged=False, strict=False, local=False, fixes=None,
 
3256
            author=None, show_diff=False, exclude=None, commit_time=None,
 
3257
            lossy=False):
 
3258
        from bzrlib.errors import (
 
3259
            PointlessCommit,
 
3260
            ConflictsInTree,
 
3261
            StrictCommitFailed
 
3262
        )
 
3263
        from bzrlib.msgeditor import (
 
3264
            edit_commit_message_encoded,
 
3265
            generate_commit_message_template,
 
3266
            make_commit_message_template_encoded,
 
3267
            set_commit_message,
 
3268
        )
 
3269
 
 
3270
        commit_stamp = offset = None
 
3271
        if commit_time is not None:
 
3272
            try:
 
3273
                commit_stamp, offset = timestamp.parse_patch_date(commit_time)
 
3274
            except ValueError, e:
 
3275
                raise errors.BzrCommandError(
 
3276
                    "Could not parse --commit-time: " + str(e))
 
3277
 
 
3278
        properties = {}
 
3279
 
 
3280
        tree, selected_list = WorkingTree.open_containing_paths(selected_list)
2035
3281
        if selected_list == ['']:
2036
3282
            # workaround - commit of root of tree should be exactly the same
2037
3283
            # as just default commit in that tree, and succeed even though
2038
3284
            # selected-file merge commit is not done yet
2039
3285
            selected_list = []
2040
3286
 
 
3287
        if fixes is None:
 
3288
            fixes = []
 
3289
        bug_property = bugtracker.encode_fixes_bug_urls(
 
3290
            self._iter_bug_fix_urls(fixes, tree.branch))
 
3291
        if bug_property:
 
3292
            properties['bugs'] = bug_property
 
3293
 
2041
3294
        if local and not tree.branch.get_bound_location():
2042
3295
            raise errors.LocalRequiresBoundBranch()
2043
3296
 
 
3297
        if message is not None:
 
3298
            try:
 
3299
                file_exists = osutils.lexists(message)
 
3300
            except UnicodeError:
 
3301
                # The commit message contains unicode characters that can't be
 
3302
                # represented in the filesystem encoding, so that can't be a
 
3303
                # file.
 
3304
                file_exists = False
 
3305
            if file_exists:
 
3306
                warning_msg = (
 
3307
                    'The commit message is a file name: "%(f)s".\n'
 
3308
                    '(use --file "%(f)s" to take commit message from that file)'
 
3309
                    % { 'f': message })
 
3310
                ui.ui_factory.show_warning(warning_msg)
 
3311
            if '\r' in message:
 
3312
                message = message.replace('\r\n', '\n')
 
3313
                message = message.replace('\r', '\n')
 
3314
            if file:
 
3315
                raise errors.BzrCommandError(
 
3316
                    "please specify either --message or --file")
 
3317
 
2044
3318
        def get_message(commit_obj):
2045
3319
            """Callback to get commit message"""
2046
 
            my_message = message
2047
 
            if my_message is None and not file:
2048
 
                template = make_commit_message_template(tree, selected_list)
2049
 
                my_message = edit_commit_message(template)
 
3320
            if file:
 
3321
                f = open(file)
 
3322
                try:
 
3323
                    my_message = f.read().decode(osutils.get_user_encoding())
 
3324
                finally:
 
3325
                    f.close()
 
3326
            elif message is not None:
 
3327
                my_message = message
 
3328
            else:
 
3329
                # No message supplied: make one up.
 
3330
                # text is the status of the tree
 
3331
                text = make_commit_message_template_encoded(tree,
 
3332
                        selected_list, diff=show_diff,
 
3333
                        output_encoding=osutils.get_user_encoding())
 
3334
                # start_message is the template generated from hooks
 
3335
                # XXX: Warning - looks like hooks return unicode,
 
3336
                # make_commit_message_template_encoded returns user encoding.
 
3337
                # We probably want to be using edit_commit_message instead to
 
3338
                # avoid this.
 
3339
                my_message = set_commit_message(commit_obj)
 
3340
                if my_message is None:
 
3341
                    start_message = generate_commit_message_template(commit_obj)
 
3342
                    my_message = edit_commit_message_encoded(text,
 
3343
                        start_message=start_message)
2050
3344
                if my_message is None:
2051
3345
                    raise errors.BzrCommandError("please specify a commit"
2052
3346
                        " message with either --message or --file")
2053
 
            elif my_message and file:
2054
 
                raise errors.BzrCommandError(
2055
 
                    "please specify either --message or --file")
2056
 
            if file:
2057
 
                my_message = codecs.open(file, 'rt', 
2058
 
                                         bzrlib.user_encoding).read()
2059
 
            if my_message == "":
2060
 
                raise errors.BzrCommandError("empty commit message specified")
 
3347
                if my_message == "":
 
3348
                    raise errors.BzrCommandError("Empty commit message specified."
 
3349
                            " Please specify a commit message with either"
 
3350
                            " --message or --file or leave a blank message"
 
3351
                            " with --message \"\".")
2061
3352
            return my_message
2062
 
        
2063
 
        if verbose:
2064
 
            reporter = ReportCommitToLog()
2065
 
        else:
2066
 
            reporter = NullCommitReporter()
2067
3353
 
 
3354
        # The API permits a commit with a filter of [] to mean 'select nothing'
 
3355
        # but the command line should not do that.
 
3356
        if not selected_list:
 
3357
            selected_list = None
2068
3358
        try:
2069
3359
            tree.commit(message_callback=get_message,
2070
3360
                        specific_files=selected_list,
2071
3361
                        allow_pointless=unchanged, strict=strict, local=local,
2072
 
                        reporter=reporter)
 
3362
                        reporter=None, verbose=verbose, revprops=properties,
 
3363
                        authors=author, timestamp=commit_stamp,
 
3364
                        timezone=offset,
 
3365
                        exclude=tree.safe_relpath_files(exclude),
 
3366
                        lossy=lossy)
2073
3367
        except PointlessCommit:
2074
 
            # FIXME: This should really happen before the file is read in;
2075
 
            # perhaps prepare the commit; get the message; then actually commit
2076
 
            raise errors.BzrCommandError("no changes to commit."
2077
 
                              " use --unchanged to commit anyhow")
 
3368
            raise errors.BzrCommandError("No changes to commit."
 
3369
                " Please 'bzr add' the files you want to commit, or use"
 
3370
                " --unchanged to force an empty commit.")
2078
3371
        except ConflictsInTree:
2079
3372
            raise errors.BzrCommandError('Conflicts detected in working '
2080
3373
                'tree.  Use "bzr conflicts" to list, "bzr resolve FILE" to'
2083
3376
            raise errors.BzrCommandError("Commit refused because there are"
2084
3377
                              " unknown files in the working tree.")
2085
3378
        except errors.BoundBranchOutOfDate, e:
2086
 
            raise errors.BzrCommandError(str(e) + "\n"
2087
 
            'To commit to master branch, run update and then commit.\n'
2088
 
            'You can also pass --local to commit to continue working '
2089
 
            'disconnected.')
 
3379
            e.extra_help = ("\n"
 
3380
                'To commit to master branch, run update and then commit.\n'
 
3381
                'You can also pass --local to commit to continue working '
 
3382
                'disconnected.')
 
3383
            raise
2090
3384
 
2091
3385
 
2092
3386
class cmd_check(Command):
2093
 
    """Validate consistency of branch history.
2094
 
 
2095
 
    This command checks various invariants about the branch storage to
2096
 
    detect data corruption or bzr bugs.
 
3387
    __doc__ = """Validate working tree structure, branch consistency and repository history.
 
3388
 
 
3389
    This command checks various invariants about branch and repository storage
 
3390
    to detect data corruption or bzr bugs.
 
3391
 
 
3392
    The working tree and branch checks will only give output if a problem is
 
3393
    detected. The output fields of the repository check are:
 
3394
 
 
3395
    revisions
 
3396
        This is just the number of revisions checked.  It doesn't
 
3397
        indicate a problem.
 
3398
 
 
3399
    versionedfiles
 
3400
        This is just the number of versionedfiles checked.  It
 
3401
        doesn't indicate a problem.
 
3402
 
 
3403
    unreferenced ancestors
 
3404
        Texts that are ancestors of other texts, but
 
3405
        are not properly referenced by the revision ancestry.  This is a
 
3406
        subtle problem that Bazaar can work around.
 
3407
 
 
3408
    unique file texts
 
3409
        This is the total number of unique file contents
 
3410
        seen in the checked revisions.  It does not indicate a problem.
 
3411
 
 
3412
    repeated file texts
 
3413
        This is the total number of repeated texts seen
 
3414
        in the checked revisions.  Texts can be repeated when their file
 
3415
        entries are modified, but the file contents are not.  It does not
 
3416
        indicate a problem.
 
3417
 
 
3418
    If no restrictions are specified, all Bazaar data that is found at the given
 
3419
    location will be checked.
 
3420
 
 
3421
    :Examples:
 
3422
 
 
3423
        Check the tree and branch at 'foo'::
 
3424
 
 
3425
            bzr check --tree --branch foo
 
3426
 
 
3427
        Check only the repository at 'bar'::
 
3428
 
 
3429
            bzr check --repo bar
 
3430
 
 
3431
        Check everything at 'baz'::
 
3432
 
 
3433
            bzr check baz
2097
3434
    """
2098
 
    takes_args = ['branch?']
2099
 
    takes_options = ['verbose']
2100
 
 
2101
 
    def run(self, branch=None, verbose=False):
2102
 
        from bzrlib.check import check
2103
 
        if branch is None:
2104
 
            tree = WorkingTree.open_containing()[0]
2105
 
            branch = tree.branch
2106
 
        else:
2107
 
            branch = Branch.open(branch)
2108
 
        check(branch, verbose)
 
3435
 
 
3436
    _see_also = ['reconcile']
 
3437
    takes_args = ['path?']
 
3438
    takes_options = ['verbose',
 
3439
                     Option('branch', help="Check the branch related to the"
 
3440
                                           " current directory."),
 
3441
                     Option('repo', help="Check the repository related to the"
 
3442
                                         " current directory."),
 
3443
                     Option('tree', help="Check the working tree related to"
 
3444
                                         " the current directory.")]
 
3445
 
 
3446
    def run(self, path=None, verbose=False, branch=False, repo=False,
 
3447
            tree=False):
 
3448
        from bzrlib.check import check_dwim
 
3449
        if path is None:
 
3450
            path = '.'
 
3451
        if not branch and not repo and not tree:
 
3452
            branch = repo = tree = True
 
3453
        check_dwim(path, verbose, do_branch=branch, do_repo=repo, do_tree=tree)
2109
3454
 
2110
3455
 
2111
3456
class cmd_upgrade(Command):
2112
 
    """Upgrade branch storage to current format.
2113
 
 
2114
 
    The check command or bzr developers may sometimes advise you to run
2115
 
    this command. When the default format has changed you may also be warned
2116
 
    during other operations to upgrade.
 
3457
    __doc__ = """Upgrade a repository, branch or working tree to a newer format.
 
3458
 
 
3459
    When the default format has changed after a major new release of
 
3460
    Bazaar, you may be informed during certain operations that you
 
3461
    should upgrade. Upgrading to a newer format may improve performance
 
3462
    or make new features available. It may however limit interoperability
 
3463
    with older repositories or with older versions of Bazaar.
 
3464
 
 
3465
    If you wish to upgrade to a particular format rather than the
 
3466
    current default, that can be specified using the --format option.
 
3467
    As a consequence, you can use the upgrade command this way to
 
3468
    "downgrade" to an earlier format, though some conversions are
 
3469
    a one way process (e.g. changing from the 1.x default to the
 
3470
    2.x default) so downgrading is not always possible.
 
3471
 
 
3472
    A backup.bzr.~#~ directory is created at the start of the conversion
 
3473
    process (where # is a number). By default, this is left there on
 
3474
    completion. If the conversion fails, delete the new .bzr directory
 
3475
    and rename this one back in its place. Use the --clean option to ask
 
3476
    for the backup.bzr directory to be removed on successful conversion.
 
3477
    Alternatively, you can delete it by hand if everything looks good
 
3478
    afterwards.
 
3479
 
 
3480
    If the location given is a shared repository, dependent branches
 
3481
    are also converted provided the repository converts successfully.
 
3482
    If the conversion of a branch fails, remaining branches are still
 
3483
    tried.
 
3484
 
 
3485
    For more information on upgrades, see the Bazaar Upgrade Guide,
 
3486
    http://doc.bazaar.canonical.com/latest/en/upgrade-guide/.
2117
3487
    """
 
3488
 
 
3489
    _see_also = ['check', 'reconcile', 'formats']
2118
3490
    takes_args = ['url?']
2119
3491
    takes_options = [
2120
 
                    RegistryOption('format',
2121
 
                        help='Upgrade to a specific format.  See "bzr help'
2122
 
                             ' formats" for details',
2123
 
                        registry=bzrdir.format_registry,
2124
 
                        converter=bzrdir.format_registry.make_bzrdir,
2125
 
                        value_switches=True, title='Branch format'),
2126
 
                    ]
2127
 
 
2128
 
 
2129
 
    def run(self, url='.', format=None):
 
3492
        RegistryOption('format',
 
3493
            help='Upgrade to a specific format.  See "bzr help'
 
3494
                 ' formats" for details.',
 
3495
            lazy_registry=('bzrlib.bzrdir', 'format_registry'),
 
3496
            converter=lambda name: bzrdir.format_registry.make_bzrdir(name),
 
3497
            value_switches=True, title='Branch format'),
 
3498
        Option('clean',
 
3499
            help='Remove the backup.bzr directory if successful.'),
 
3500
        Option('dry-run',
 
3501
            help="Show what would be done, but don't actually do anything."),
 
3502
    ]
 
3503
 
 
3504
    def run(self, url='.', format=None, clean=False, dry_run=False):
2130
3505
        from bzrlib.upgrade import upgrade
2131
 
        if format is None:
2132
 
            format = bzrdir.format_registry.make_bzrdir('default')
2133
 
        upgrade(url, format)
 
3506
        exceptions = upgrade(url, format, clean_up=clean, dry_run=dry_run)
 
3507
        if exceptions:
 
3508
            if len(exceptions) == 1:
 
3509
                # Compatibility with historical behavior
 
3510
                raise exceptions[0]
 
3511
            else:
 
3512
                return 3
2134
3513
 
2135
3514
 
2136
3515
class cmd_whoami(Command):
2137
 
    """Show or set bzr user id.
2138
 
    
2139
 
    examples:
2140
 
        bzr whoami --email
2141
 
        bzr whoami 'Frank Chu <fchu@example.com>'
 
3516
    __doc__ = """Show or set bzr user id.
 
3517
 
 
3518
    :Examples:
 
3519
        Show the email of the current user::
 
3520
 
 
3521
            bzr whoami --email
 
3522
 
 
3523
        Set the current user::
 
3524
 
 
3525
            bzr whoami "Frank Chu <fchu@example.com>"
2142
3526
    """
2143
 
    takes_options = [ Option('email',
2144
 
                             help='display email address only'),
 
3527
    takes_options = [ 'directory',
 
3528
                      Option('email',
 
3529
                             help='Display email address only.'),
2145
3530
                      Option('branch',
2146
 
                             help='set identity for the current branch instead of '
2147
 
                                  'globally'),
 
3531
                             help='Set identity for the current branch instead of '
 
3532
                                  'globally.'),
2148
3533
                    ]
2149
3534
    takes_args = ['name?']
2150
3535
    encoding_type = 'replace'
2151
 
    
 
3536
 
2152
3537
    @display_command
2153
 
    def run(self, email=False, branch=False, name=None):
 
3538
    def run(self, email=False, branch=False, name=None, directory=None):
2154
3539
        if name is None:
2155
 
            # use branch if we're inside one; otherwise global config
2156
 
            try:
2157
 
                c = Branch.open_containing('.')[0].get_config()
2158
 
            except errors.NotBranchError:
2159
 
                c = config.GlobalConfig()
 
3540
            if directory is None:
 
3541
                # use branch if we're inside one; otherwise global config
 
3542
                try:
 
3543
                    c = Branch.open_containing(u'.')[0].get_config()
 
3544
                except errors.NotBranchError:
 
3545
                    c = _mod_config.GlobalConfig()
 
3546
            else:
 
3547
                c = Branch.open(directory).get_config()
2160
3548
            if email:
2161
3549
                self.outf.write(c.user_email() + '\n')
2162
3550
            else:
2163
3551
                self.outf.write(c.username() + '\n')
2164
3552
            return
2165
3553
 
 
3554
        if email:
 
3555
            raise errors.BzrCommandError("--email can only be used to display existing "
 
3556
                                         "identity")
 
3557
 
2166
3558
        # display a warning if an email address isn't included in the given name.
2167
3559
        try:
2168
 
            config.extract_email_address(name)
 
3560
            _mod_config.extract_email_address(name)
2169
3561
        except errors.NoEmailInUsername, e:
2170
3562
            warning('"%s" does not seem to contain an email address.  '
2171
3563
                    'This is allowed, but not recommended.', name)
2172
 
        
 
3564
 
2173
3565
        # use global config unless --branch given
2174
3566
        if branch:
2175
 
            c = Branch.open_containing('.')[0].get_config()
 
3567
            if directory is None:
 
3568
                c = Branch.open_containing(u'.')[0].get_config()
 
3569
            else:
 
3570
                c = Branch.open(directory).get_config()
2176
3571
        else:
2177
 
            c = config.GlobalConfig()
 
3572
            c = _mod_config.GlobalConfig()
2178
3573
        c.set_user_option('email', name)
2179
3574
 
2180
3575
 
2181
3576
class cmd_nick(Command):
2182
 
    """Print or set the branch nickname.  
2183
 
 
2184
 
    If unset, the tree root directory name is used as the nickname
2185
 
    To print the current nickname, execute with no argument.  
 
3577
    __doc__ = """Print or set the branch nickname.
 
3578
 
 
3579
    If unset, the tree root directory name is used as the nickname.
 
3580
    To print the current nickname, execute with no argument.
 
3581
 
 
3582
    Bound branches use the nickname of its master branch unless it is set
 
3583
    locally.
2186
3584
    """
 
3585
 
 
3586
    _see_also = ['info']
2187
3587
    takes_args = ['nickname?']
2188
 
    def run(self, nickname=None):
2189
 
        branch = Branch.open_containing(u'.')[0]
 
3588
    takes_options = ['directory']
 
3589
    def run(self, nickname=None, directory=u'.'):
 
3590
        branch = Branch.open_containing(directory)[0]
2190
3591
        if nickname is None:
2191
3592
            self.printme(branch)
2192
3593
        else:
2194
3595
 
2195
3596
    @display_command
2196
3597
    def printme(self, branch):
2197
 
        print branch.nick 
 
3598
        self.outf.write('%s\n' % branch.nick)
 
3599
 
 
3600
 
 
3601
class cmd_alias(Command):
 
3602
    __doc__ = """Set/unset and display aliases.
 
3603
 
 
3604
    :Examples:
 
3605
        Show the current aliases::
 
3606
 
 
3607
            bzr alias
 
3608
 
 
3609
        Show the alias specified for 'll'::
 
3610
 
 
3611
            bzr alias ll
 
3612
 
 
3613
        Set an alias for 'll'::
 
3614
 
 
3615
            bzr alias ll="log --line -r-10..-1"
 
3616
 
 
3617
        To remove an alias for 'll'::
 
3618
 
 
3619
            bzr alias --remove ll
 
3620
 
 
3621
    """
 
3622
    takes_args = ['name?']
 
3623
    takes_options = [
 
3624
        Option('remove', help='Remove the alias.'),
 
3625
        ]
 
3626
 
 
3627
    def run(self, name=None, remove=False):
 
3628
        if remove:
 
3629
            self.remove_alias(name)
 
3630
        elif name is None:
 
3631
            self.print_aliases()
 
3632
        else:
 
3633
            equal_pos = name.find('=')
 
3634
            if equal_pos == -1:
 
3635
                self.print_alias(name)
 
3636
            else:
 
3637
                self.set_alias(name[:equal_pos], name[equal_pos+1:])
 
3638
 
 
3639
    def remove_alias(self, alias_name):
 
3640
        if alias_name is None:
 
3641
            raise errors.BzrCommandError(
 
3642
                'bzr alias --remove expects an alias to remove.')
 
3643
        # If alias is not found, print something like:
 
3644
        # unalias: foo: not found
 
3645
        c = _mod_config.GlobalConfig()
 
3646
        c.unset_alias(alias_name)
 
3647
 
 
3648
    @display_command
 
3649
    def print_aliases(self):
 
3650
        """Print out the defined aliases in a similar format to bash."""
 
3651
        aliases = _mod_config.GlobalConfig().get_aliases()
 
3652
        for key, value in sorted(aliases.iteritems()):
 
3653
            self.outf.write('bzr alias %s="%s"\n' % (key, value))
 
3654
 
 
3655
    @display_command
 
3656
    def print_alias(self, alias_name):
 
3657
        from bzrlib.commands import get_alias
 
3658
        alias = get_alias(alias_name)
 
3659
        if alias is None:
 
3660
            self.outf.write("bzr alias: %s: not found\n" % alias_name)
 
3661
        else:
 
3662
            self.outf.write(
 
3663
                'bzr alias %s="%s"\n' % (alias_name, ' '.join(alias)))
 
3664
 
 
3665
    def set_alias(self, alias_name, alias_command):
 
3666
        """Save the alias in the global config."""
 
3667
        c = _mod_config.GlobalConfig()
 
3668
        c.set_alias(alias_name, alias_command)
2198
3669
 
2199
3670
 
2200
3671
class cmd_selftest(Command):
2201
 
    """Run internal test suite.
2202
 
    
2203
 
    This creates temporary test directories in the working directory, but not
2204
 
    existing data is affected.  These directories are deleted if the tests
2205
 
    pass, or left behind to help in debugging if they fail and --keep-output
2206
 
    is specified.
2207
 
    
 
3672
    __doc__ = """Run internal test suite.
 
3673
 
2208
3674
    If arguments are given, they are regular expressions that say which tests
2209
3675
    should run.  Tests matching any expression are run, and other tests are
2210
3676
    not run.
2213
3679
    all other tests are run.  This is useful if you have been working in a
2214
3680
    particular area, but want to make sure nothing else was broken.
2215
3681
 
 
3682
    If --exclude is given, tests that match that regular expression are
 
3683
    excluded, regardless of whether they match --first or not.
 
3684
 
 
3685
    To help catch accidential dependencies between tests, the --randomize
 
3686
    option is useful. In most cases, the argument used is the word 'now'.
 
3687
    Note that the seed used for the random number generator is displayed
 
3688
    when this option is used. The seed can be explicitly passed as the
 
3689
    argument to this option if required. This enables reproduction of the
 
3690
    actual ordering used if and when an order sensitive problem is encountered.
 
3691
 
 
3692
    If --list-only is given, the tests that would be run are listed. This is
 
3693
    useful when combined with --first, --exclude and/or --randomize to
 
3694
    understand their impact. The test harness reports "Listed nn tests in ..."
 
3695
    instead of "Ran nn tests in ..." when list mode is enabled.
 
3696
 
2216
3697
    If the global option '--no-plugins' is given, plugins are not loaded
2217
3698
    before running the selftests.  This has two effects: features provided or
2218
3699
    modified by plugins will not be tested, and tests provided by plugins will
2219
3700
    not be run.
2220
3701
 
2221
 
    examples::
2222
 
        bzr selftest ignore
2223
 
            run only tests relating to 'ignore'
2224
 
        bzr --no-plugins selftest -v
2225
 
            disable plugins and list tests as they're run
 
3702
    Tests that need working space on disk use a common temporary directory,
 
3703
    typically inside $TMPDIR or /tmp.
 
3704
 
 
3705
    If you set BZR_TEST_PDB=1 when running selftest, failing tests will drop
 
3706
    into a pdb postmortem session.
 
3707
 
 
3708
    The --coverage=DIRNAME global option produces a report with covered code
 
3709
    indicated.
 
3710
 
 
3711
    :Examples:
 
3712
        Run only tests relating to 'ignore'::
 
3713
 
 
3714
            bzr selftest ignore
 
3715
 
 
3716
        Disable plugins and list tests as they're run::
 
3717
 
 
3718
            bzr --no-plugins selftest -v
2226
3719
    """
2227
 
    # TODO: --list should give a list of all available tests
2228
 
 
2229
3720
    # NB: this is used from the class without creating an instance, which is
2230
3721
    # why it does not have a self parameter.
2231
3722
    def get_transport_type(typestring):
2232
3723
        """Parse and return a transport specifier."""
2233
3724
        if typestring == "sftp":
2234
 
            from bzrlib.transport.sftp import SFTPAbsoluteServer
2235
 
            return SFTPAbsoluteServer
2236
 
        if typestring == "memory":
2237
 
            from bzrlib.transport.memory import MemoryServer
2238
 
            return MemoryServer
2239
 
        if typestring == "fakenfs":
2240
 
            from bzrlib.transport.fakenfs import FakeNFSServer
2241
 
            return FakeNFSServer
 
3725
            from bzrlib.tests import stub_sftp
 
3726
            return stub_sftp.SFTPAbsoluteServer
 
3727
        elif typestring == "memory":
 
3728
            from bzrlib.tests import test_server
 
3729
            return memory.MemoryServer
 
3730
        elif typestring == "fakenfs":
 
3731
            from bzrlib.tests import test_server
 
3732
            return test_server.FakeNFSServer
2242
3733
        msg = "No known transport type %s. Supported types are: sftp\n" %\
2243
3734
            (typestring)
2244
3735
        raise errors.BzrCommandError(msg)
2246
3737
    hidden = True
2247
3738
    takes_args = ['testspecs*']
2248
3739
    takes_options = ['verbose',
2249
 
                     Option('one', help='stop when one test fails'),
2250
 
                     Option('keep-output', 
2251
 
                            help='keep output directories when tests fail'),
2252
 
                     Option('transport', 
 
3740
                     Option('one',
 
3741
                             help='Stop when one test fails.',
 
3742
                             short_name='1',
 
3743
                             ),
 
3744
                     Option('transport',
2253
3745
                            help='Use a different transport by default '
2254
3746
                                 'throughout the test suite.',
2255
3747
                            type=get_transport_type),
2256
 
                     Option('benchmark', help='run the bzr bencharks.'),
 
3748
                     Option('benchmark',
 
3749
                            help='Run the benchmarks rather than selftests.',
 
3750
                            hidden=True),
2257
3751
                     Option('lsprof-timed',
2258
 
                            help='generate lsprof output for benchmarked'
 
3752
                            help='Generate lsprof output for benchmarked'
2259
3753
                                 ' sections of code.'),
2260
 
                     Option('cache-dir', type=str,
2261
 
                            help='a directory to cache intermediate'
2262
 
                                 ' benchmark steps'),
2263
 
                     Option('clean-output',
2264
 
                            help='clean temporary tests directories'
2265
 
                                 ' without running tests'),
 
3754
                     Option('lsprof-tests',
 
3755
                            help='Generate lsprof output for each test.'),
2266
3756
                     Option('first',
2267
 
                            help='run all tests, but run specified tests first',
2268
 
                            )
 
3757
                            help='Run all tests, but run specified tests first.',
 
3758
                            short_name='f',
 
3759
                            ),
 
3760
                     Option('list-only',
 
3761
                            help='List the tests instead of running them.'),
 
3762
                     RegistryOption('parallel',
 
3763
                        help="Run the test suite in parallel.",
 
3764
                        lazy_registry=('bzrlib.tests', 'parallel_registry'),
 
3765
                        value_switches=False,
 
3766
                        ),
 
3767
                     Option('randomize', type=str, argname="SEED",
 
3768
                            help='Randomize the order of tests using the given'
 
3769
                                 ' seed or "now" for the current time.'),
 
3770
                     ListOption('exclude', type=str, argname="PATTERN",
 
3771
                                short_name='x',
 
3772
                                help='Exclude tests that match this regular'
 
3773
                                ' expression.'),
 
3774
                     Option('subunit',
 
3775
                        help='Output test progress via subunit.'),
 
3776
                     Option('strict', help='Fail on missing dependencies or '
 
3777
                            'known failures.'),
 
3778
                     Option('load-list', type=str, argname='TESTLISTFILE',
 
3779
                            help='Load a test id list from a text file.'),
 
3780
                     ListOption('debugflag', type=str, short_name='E',
 
3781
                                help='Turn on a selftest debug flag.'),
 
3782
                     ListOption('starting-with', type=str, argname='TESTID',
 
3783
                                param_name='starting_with', short_name='s',
 
3784
                                help=
 
3785
                                'Load only the tests starting with TESTID.'),
2269
3786
                     ]
2270
3787
    encoding_type = 'replace'
2271
3788
 
2272
 
    def run(self, testspecs_list=None, verbose=None, one=False,
2273
 
            keep_output=False, transport=None, benchmark=None,
2274
 
            lsprof_timed=None, cache_dir=None, clean_output=False,
2275
 
            first=False):
2276
 
        import bzrlib.ui
2277
 
        from bzrlib.tests import selftest
2278
 
        import bzrlib.benchmarks as benchmarks
2279
 
        from bzrlib.benchmarks import tree_creator
2280
 
 
2281
 
        if clean_output:
2282
 
            from bzrlib.tests import clean_selftest_output
2283
 
            clean_selftest_output()
2284
 
            return 0
2285
 
 
2286
 
        if cache_dir is not None:
2287
 
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2288
 
        print '%10s: %s' % ('bzr', osutils.realpath(sys.argv[0]))
2289
 
        print '%10s: %s' % ('bzrlib', bzrlib.__path__[0])
2290
 
        print
 
3789
    def __init__(self):
 
3790
        Command.__init__(self)
 
3791
        self.additional_selftest_args = {}
 
3792
 
 
3793
    def run(self, testspecs_list=None, verbose=False, one=False,
 
3794
            transport=None, benchmark=None,
 
3795
            lsprof_timed=None,
 
3796
            first=False, list_only=False,
 
3797
            randomize=None, exclude=None, strict=False,
 
3798
            load_list=None, debugflag=None, starting_with=None, subunit=False,
 
3799
            parallel=None, lsprof_tests=False):
 
3800
        from bzrlib import tests
 
3801
 
2291
3802
        if testspecs_list is not None:
2292
3803
            pattern = '|'.join(testspecs_list)
2293
3804
        else:
2294
3805
            pattern = ".*"
 
3806
        if subunit:
 
3807
            try:
 
3808
                from bzrlib.tests import SubUnitBzrRunner
 
3809
            except ImportError:
 
3810
                raise errors.BzrCommandError("subunit not available. subunit "
 
3811
                    "needs to be installed to use --subunit.")
 
3812
            self.additional_selftest_args['runner_class'] = SubUnitBzrRunner
 
3813
            # On Windows, disable automatic conversion of '\n' to '\r\n' in
 
3814
            # stdout, which would corrupt the subunit stream. 
 
3815
            # FIXME: This has been fixed in subunit trunk (>0.0.5) so the
 
3816
            # following code can be deleted when it's sufficiently deployed
 
3817
            # -- vila/mgz 20100514
 
3818
            if (sys.platform == "win32"
 
3819
                and getattr(sys.stdout, 'fileno', None) is not None):
 
3820
                import msvcrt
 
3821
                msvcrt.setmode(sys.stdout.fileno(), os.O_BINARY)
 
3822
        if parallel:
 
3823
            self.additional_selftest_args.setdefault(
 
3824
                'suite_decorators', []).append(parallel)
2295
3825
        if benchmark:
2296
 
            test_suite_factory = benchmarks.test_suite
2297
 
            if verbose is None:
2298
 
                verbose = True
2299
 
            # TODO: should possibly lock the history file...
2300
 
            benchfile = open(".perf_history", "at", buffering=1)
 
3826
            raise errors.BzrCommandError(
 
3827
                "--benchmark is no longer supported from bzr 2.2; "
 
3828
                "use bzr-usertest instead")
 
3829
        test_suite_factory = None
 
3830
        if not exclude:
 
3831
            exclude_pattern = None
2301
3832
        else:
2302
 
            test_suite_factory = None
2303
 
            if verbose is None:
2304
 
                verbose = False
2305
 
            benchfile = None
 
3833
            exclude_pattern = '(' + '|'.join(exclude) + ')'
 
3834
        selftest_kwargs = {"verbose": verbose,
 
3835
                          "pattern": pattern,
 
3836
                          "stop_on_failure": one,
 
3837
                          "transport": transport,
 
3838
                          "test_suite_factory": test_suite_factory,
 
3839
                          "lsprof_timed": lsprof_timed,
 
3840
                          "lsprof_tests": lsprof_tests,
 
3841
                          "matching_tests_first": first,
 
3842
                          "list_only": list_only,
 
3843
                          "random_seed": randomize,
 
3844
                          "exclude_pattern": exclude_pattern,
 
3845
                          "strict": strict,
 
3846
                          "load_list": load_list,
 
3847
                          "debug_flags": debugflag,
 
3848
                          "starting_with": starting_with
 
3849
                          }
 
3850
        selftest_kwargs.update(self.additional_selftest_args)
 
3851
 
 
3852
        # Make deprecation warnings visible, unless -Werror is set
 
3853
        cleanup = symbol_versioning.activate_deprecation_warnings(
 
3854
            override=False)
2306
3855
        try:
2307
 
            result = selftest(verbose=verbose, 
2308
 
                              pattern=pattern,
2309
 
                              stop_on_failure=one, 
2310
 
                              keep_output=keep_output,
2311
 
                              transport=transport,
2312
 
                              test_suite_factory=test_suite_factory,
2313
 
                              lsprof_timed=lsprof_timed,
2314
 
                              bench_history=benchfile,
2315
 
                              matching_tests_first=first,
2316
 
                              )
 
3856
            result = tests.selftest(**selftest_kwargs)
2317
3857
        finally:
2318
 
            if benchfile is not None:
2319
 
                benchfile.close()
2320
 
        if result:
2321
 
            info('tests passed')
2322
 
        else:
2323
 
            info('tests failed')
 
3858
            cleanup()
2324
3859
        return int(not result)
2325
3860
 
2326
3861
 
2327
3862
class cmd_version(Command):
2328
 
    """Show version of bzr."""
 
3863
    __doc__ = """Show version of bzr."""
 
3864
 
 
3865
    encoding_type = 'replace'
 
3866
    takes_options = [
 
3867
        Option("short", help="Print just the version number."),
 
3868
        ]
2329
3869
 
2330
3870
    @display_command
2331
 
    def run(self):
 
3871
    def run(self, short=False):
2332
3872
        from bzrlib.version import show_version
2333
 
        show_version()
 
3873
        if short:
 
3874
            self.outf.write(bzrlib.version_string + '\n')
 
3875
        else:
 
3876
            show_version(to_file=self.outf)
2334
3877
 
2335
3878
 
2336
3879
class cmd_rocks(Command):
2337
 
    """Statement of optimism."""
 
3880
    __doc__ = """Statement of optimism."""
2338
3881
 
2339
3882
    hidden = True
2340
3883
 
2341
3884
    @display_command
2342
3885
    def run(self):
2343
 
        print "it sure does!"
 
3886
        self.outf.write("It sure does!\n")
2344
3887
 
2345
3888
 
2346
3889
class cmd_find_merge_base(Command):
2347
 
    """Find and print a base revision for merging two branches."""
 
3890
    __doc__ = """Find and print a base revision for merging two branches."""
2348
3891
    # TODO: Options to specify revisions on either side, as if
2349
3892
    #       merging only part of the history.
2350
3893
    takes_args = ['branch', 'other']
2351
3894
    hidden = True
2352
 
    
 
3895
 
2353
3896
    @display_command
2354
3897
    def run(self, branch, other):
2355
 
        from bzrlib.revision import MultipleRevisionSources
2356
 
        
 
3898
        from bzrlib.revision import ensure_null
 
3899
 
2357
3900
        branch1 = Branch.open_containing(branch)[0]
2358
3901
        branch2 = Branch.open_containing(other)[0]
2359
 
 
2360
 
        last1 = branch1.last_revision()
2361
 
        last2 = branch2.last_revision()
2362
 
 
2363
 
        source = MultipleRevisionSources(branch1.repository, 
2364
 
                                         branch2.repository)
2365
 
        
2366
 
        base_rev_id = common_ancestor(last1, last2, source)
2367
 
 
2368
 
        print 'merge base is revision %s' % base_rev_id
 
3902
        self.add_cleanup(branch1.lock_read().unlock)
 
3903
        self.add_cleanup(branch2.lock_read().unlock)
 
3904
        last1 = ensure_null(branch1.last_revision())
 
3905
        last2 = ensure_null(branch2.last_revision())
 
3906
 
 
3907
        graph = branch1.repository.get_graph(branch2.repository)
 
3908
        base_rev_id = graph.find_unique_lca(last1, last2)
 
3909
 
 
3910
        self.outf.write('merge base is revision %s\n' % base_rev_id)
2369
3911
 
2370
3912
 
2371
3913
class cmd_merge(Command):
2372
 
    """Perform a three-way merge.
2373
 
    
2374
 
    The branch is the branch you will merge from.  By default, it will merge
2375
 
    the latest revision.  If you specify a revision, that revision will be
2376
 
    merged.  If you specify two revisions, the first will be used as a BASE,
2377
 
    and the second one as OTHER.  Revision numbers are always relative to the
2378
 
    specified branch.
2379
 
 
2380
 
    By default, bzr will try to merge in all new work from the other
2381
 
    branch, automatically determining an appropriate base.  If this
2382
 
    fails, you may need to give an explicit base.
2383
 
    
 
3914
    __doc__ = """Perform a three-way merge.
 
3915
 
 
3916
    The source of the merge can be specified either in the form of a branch,
 
3917
    or in the form of a path to a file containing a merge directive generated
 
3918
    with bzr send. If neither is specified, the default is the upstream branch
 
3919
    or the branch most recently merged using --remember.  The source of the
 
3920
    merge may also be specified in the form of a path to a file in another
 
3921
    branch:  in this case, only the modifications to that file are merged into
 
3922
    the current working tree.
 
3923
 
 
3924
    When merging from a branch, by default bzr will try to merge in all new
 
3925
    work from the other branch, automatically determining an appropriate base
 
3926
    revision.  If this fails, you may need to give an explicit base.
 
3927
 
 
3928
    To pick a different ending revision, pass "--revision OTHER".  bzr will
 
3929
    try to merge in all new work up to and including revision OTHER.
 
3930
 
 
3931
    If you specify two values, "--revision BASE..OTHER", only revisions BASE
 
3932
    through OTHER, excluding BASE but including OTHER, will be merged.  If this
 
3933
    causes some revisions to be skipped, i.e. if the destination branch does
 
3934
    not already contain revision BASE, such a merge is commonly referred to as
 
3935
    a "cherrypick". Unlike a normal merge, Bazaar does not currently track
 
3936
    cherrypicks. The changes look like a normal commit, and the history of the
 
3937
    changes from the other branch is not stored in the commit.
 
3938
 
 
3939
    Revision numbers are always relative to the source branch.
 
3940
 
2384
3941
    Merge will do its best to combine the changes in two branches, but there
2385
3942
    are some kinds of problems only a human can fix.  When it encounters those,
2386
3943
    it will mark a conflict.  A conflict means that you need to fix something,
2388
3945
 
2389
3946
    Use bzr resolve when you have fixed a problem.  See also bzr conflicts.
2390
3947
 
2391
 
    If there is no default branch set, the first merge will set it. After
2392
 
    that, you can omit the branch to use the default.  To change the
2393
 
    default, use --remember. The value will only be saved if the remote
2394
 
    location can be accessed.
 
3948
    If there is no default branch set, the first merge will set it (use
 
3949
    --no-remember to avoid settting it). After that, you can omit the branch
 
3950
    to use the default.  To change the default, use --remember. The value will
 
3951
    only be saved if the remote location can be accessed.
2395
3952
 
2396
3953
    The results of the merge are placed into the destination working
2397
3954
    directory, where they can be reviewed (with bzr diff), tested, and then
2398
3955
    committed to record the result of the merge.
2399
3956
 
2400
 
    Examples:
2401
 
 
2402
 
    To merge the latest revision from bzr.dev
2403
 
    bzr merge ../bzr.dev
2404
 
 
2405
 
    To merge changes up to and including revision 82 from bzr.dev
2406
 
    bzr merge -r 82 ../bzr.dev
2407
 
 
2408
 
    To merge the changes introduced by 82, without previous changes:
2409
 
    bzr merge -r 81..82 ../bzr.dev
2410
 
    
2411
3957
    merge refuses to run if there are any uncommitted changes, unless
2412
 
    --force is given.
2413
 
 
2414
 
    The following merge types are available:
 
3958
    --force is given.  If --force is given, then the changes from the source 
 
3959
    will be merged with the current working tree, including any uncommitted
 
3960
    changes in the tree.  The --force option can also be used to create a
 
3961
    merge revision which has more than two parents.
 
3962
 
 
3963
    If one would like to merge changes from the working tree of the other
 
3964
    branch without merging any committed revisions, the --uncommitted option
 
3965
    can be given.
 
3966
 
 
3967
    To select only some changes to merge, use "merge -i", which will prompt
 
3968
    you to apply each diff hunk and file change, similar to "shelve".
 
3969
 
 
3970
    :Examples:
 
3971
        To merge all new revisions from bzr.dev::
 
3972
 
 
3973
            bzr merge ../bzr.dev
 
3974
 
 
3975
        To merge changes up to and including revision 82 from bzr.dev::
 
3976
 
 
3977
            bzr merge -r 82 ../bzr.dev
 
3978
 
 
3979
        To merge the changes introduced by 82, without previous changes::
 
3980
 
 
3981
            bzr merge -r 81..82 ../bzr.dev
 
3982
 
 
3983
        To apply a merge directive contained in /tmp/merge::
 
3984
 
 
3985
            bzr merge /tmp/merge
 
3986
 
 
3987
        To create a merge revision with three parents from two branches
 
3988
        feature1a and feature1b:
 
3989
 
 
3990
            bzr merge ../feature1a
 
3991
            bzr merge ../feature1b --force
 
3992
            bzr commit -m 'revision with three parents'
2415
3993
    """
2416
 
    takes_args = ['branch?']
2417
 
    takes_options = ['revision', 'force', 'merge-type', 'reprocess', 'remember',
 
3994
 
 
3995
    encoding_type = 'exact'
 
3996
    _see_also = ['update', 'remerge', 'status-flags', 'send']
 
3997
    takes_args = ['location?']
 
3998
    takes_options = [
 
3999
        'change',
 
4000
        'revision',
 
4001
        Option('force',
 
4002
               help='Merge even if the destination tree has uncommitted changes.'),
 
4003
        'merge-type',
 
4004
        'reprocess',
 
4005
        'remember',
2418
4006
        Option('show-base', help="Show base revision text in "
2419
 
               "conflicts"),
 
4007
               "conflicts."),
2420
4008
        Option('uncommitted', help='Apply uncommitted changes'
2421
 
               ' from a working copy, instead of branch changes'),
 
4009
               ' from a working copy, instead of branch changes.'),
2422
4010
        Option('pull', help='If the destination is already'
2423
4011
                ' completely merged into the source, pull from the'
2424
 
                ' source rather than merging. When this happens,'
 
4012
                ' source rather than merging.  When this happens,'
2425
4013
                ' you do not need to commit the result.'),
2426
 
        Option('directory',
2427
 
            help='branch to merge into, '
2428
 
                 'rather than the one containing the working directory',
2429
 
            short_name='d',
2430
 
            type=unicode,
2431
 
            ),
 
4014
        custom_help('directory',
 
4015
               help='Branch to merge into, '
 
4016
                    'rather than the one containing the working directory.'),
 
4017
        Option('preview', help='Instead of merging, show a diff of the'
 
4018
               ' merge.'),
 
4019
        Option('interactive', help='Select changes interactively.',
 
4020
            short_name='i')
2432
4021
    ]
2433
4022
 
2434
 
    def run(self, branch=None, revision=None, force=False, merge_type=None,
2435
 
            show_base=False, reprocess=False, remember=False,
 
4023
    def run(self, location=None, revision=None, force=False,
 
4024
            merge_type=None, show_base=False, reprocess=None, remember=None,
2436
4025
            uncommitted=False, pull=False,
2437
4026
            directory=None,
 
4027
            preview=False,
 
4028
            interactive=False,
2438
4029
            ):
2439
4030
        if merge_type is None:
2440
4031
            merge_type = _mod_merge.Merge3Merger
2441
4032
 
2442
4033
        if directory is None: directory = u'.'
 
4034
        possible_transports = []
 
4035
        merger = None
 
4036
        allow_pending = True
 
4037
        verified = 'inapplicable'
 
4038
 
2443
4039
        tree = WorkingTree.open_containing(directory)[0]
2444
 
        change_reporter = delta.ChangeReporter(tree.inventory)
2445
 
 
2446
 
        if branch is not None:
 
4040
        if tree.branch.revno() == 0:
 
4041
            raise errors.BzrCommandError('Merging into empty branches not currently supported, '
 
4042
                                         'https://bugs.launchpad.net/bzr/+bug/308562')
 
4043
 
 
4044
        try:
 
4045
            basis_tree = tree.revision_tree(tree.last_revision())
 
4046
        except errors.NoSuchRevision:
 
4047
            basis_tree = tree.basis_tree()
 
4048
 
 
4049
        # die as quickly as possible if there are uncommitted changes
 
4050
        if not force:
 
4051
            if tree.has_changes():
 
4052
                raise errors.UncommittedChanges(tree)
 
4053
 
 
4054
        view_info = _get_view_info_for_change_reporter(tree)
 
4055
        change_reporter = delta._ChangeReporter(
 
4056
            unversioned_filter=tree.is_ignored, view_info=view_info)
 
4057
        pb = ui.ui_factory.nested_progress_bar()
 
4058
        self.add_cleanup(pb.finished)
 
4059
        self.add_cleanup(tree.lock_write().unlock)
 
4060
        if location is not None:
2447
4061
            try:
2448
 
                reader = bundle.read_bundle_from_url(branch)
 
4062
                mergeable = bundle.read_mergeable_from_url(location,
 
4063
                    possible_transports=possible_transports)
2449
4064
            except errors.NotABundle:
2450
 
                pass # Continue on considering this url a Branch
2451
 
            else:
2452
 
                conflicts = merge_bundle(reader, tree, not force, merge_type,
2453
 
                                         reprocess, show_base, change_reporter)
2454
 
                if conflicts == 0:
2455
 
                    return 0
2456
 
                else:
2457
 
                    return 1
2458
 
 
2459
 
        if revision is None \
2460
 
                or len(revision) < 1 or revision[0].needs_branch():
2461
 
            branch = self._get_remembered_parent(tree, branch, 'Merging from')
2462
 
 
2463
 
        if revision is None or len(revision) < 1:
2464
 
            if uncommitted:
2465
 
                base = [branch, -1]
2466
 
                other = [branch, None]
2467
 
            else:
2468
 
                base = [None, None]
2469
 
                other = [branch, -1]
2470
 
            other_branch, path = Branch.open_containing(branch)
2471
 
        else:
2472
 
            if uncommitted:
 
4065
                mergeable = None
 
4066
            else:
 
4067
                if uncommitted:
 
4068
                    raise errors.BzrCommandError('Cannot use --uncommitted'
 
4069
                        ' with bundles or merge directives.')
 
4070
 
 
4071
                if revision is not None:
 
4072
                    raise errors.BzrCommandError(
 
4073
                        'Cannot use -r with merge directives or bundles')
 
4074
                merger, verified = _mod_merge.Merger.from_mergeable(tree,
 
4075
                   mergeable, None)
 
4076
 
 
4077
        if merger is None and uncommitted:
 
4078
            if revision is not None and len(revision) > 0:
2473
4079
                raise errors.BzrCommandError('Cannot use --uncommitted and'
2474
 
                                             ' --revision at the same time.')
2475
 
            branch = revision[0].get_branch() or branch
2476
 
            if len(revision) == 1:
2477
 
                base = [None, None]
2478
 
                other_branch, path = Branch.open_containing(branch)
2479
 
                revno = revision[0].in_history(other_branch).revno
2480
 
                other = [branch, revno]
2481
 
            else:
2482
 
                assert len(revision) == 2
2483
 
                if None in revision:
2484
 
                    raise errors.BzrCommandError(
2485
 
                        "Merge doesn't permit empty revision specifier.")
2486
 
                base_branch, path = Branch.open_containing(branch)
2487
 
                branch1 = revision[1].get_branch() or branch
2488
 
                other_branch, path1 = Branch.open_containing(branch1)
2489
 
                if revision[0].get_branch() is not None:
2490
 
                    # then path was obtained from it, and is None.
2491
 
                    path = path1
2492
 
 
2493
 
                base = [branch, revision[0].in_history(base_branch).revno]
2494
 
                other = [branch1, revision[1].in_history(other_branch).revno]
2495
 
 
2496
 
        if tree.branch.get_parent() is None or remember:
2497
 
            tree.branch.set_parent(other_branch.base)
2498
 
 
2499
 
        if path != "":
2500
 
            interesting_files = [path]
2501
 
        else:
2502
 
            interesting_files = None
2503
 
        pb = ui.ui_factory.nested_progress_bar()
 
4080
                    ' --revision at the same time.')
 
4081
            merger = self.get_merger_from_uncommitted(tree, location, None)
 
4082
            allow_pending = False
 
4083
 
 
4084
        if merger is None:
 
4085
            merger, allow_pending = self._get_merger_from_branch(tree,
 
4086
                location, revision, remember, possible_transports, None)
 
4087
 
 
4088
        merger.merge_type = merge_type
 
4089
        merger.reprocess = reprocess
 
4090
        merger.show_base = show_base
 
4091
        self.sanity_check_merger(merger)
 
4092
        if (merger.base_rev_id == merger.other_rev_id and
 
4093
            merger.other_rev_id is not None):
 
4094
            # check if location is a nonexistent file (and not a branch) to
 
4095
            # disambiguate the 'Nothing to do'
 
4096
            if merger.interesting_files:
 
4097
                if not merger.other_tree.has_filename(
 
4098
                    merger.interesting_files[0]):
 
4099
                    note("merger: " + str(merger))
 
4100
                    raise errors.PathsDoNotExist([location])
 
4101
            note('Nothing to do.')
 
4102
            return 0
 
4103
        if pull and not preview:
 
4104
            if merger.interesting_files is not None:
 
4105
                raise errors.BzrCommandError('Cannot pull individual files')
 
4106
            if (merger.base_rev_id == tree.last_revision()):
 
4107
                result = tree.pull(merger.other_branch, False,
 
4108
                                   merger.other_rev_id)
 
4109
                result.report(self.outf)
 
4110
                return 0
 
4111
        if merger.this_basis is None:
 
4112
            raise errors.BzrCommandError(
 
4113
                "This branch has no commits."
 
4114
                " (perhaps you would prefer 'bzr pull')")
 
4115
        if preview:
 
4116
            return self._do_preview(merger)
 
4117
        elif interactive:
 
4118
            return self._do_interactive(merger)
 
4119
        else:
 
4120
            return self._do_merge(merger, change_reporter, allow_pending,
 
4121
                                  verified)
 
4122
 
 
4123
    def _get_preview(self, merger):
 
4124
        tree_merger = merger.make_merger()
 
4125
        tt = tree_merger.make_preview_transform()
 
4126
        self.add_cleanup(tt.finalize)
 
4127
        result_tree = tt.get_preview_tree()
 
4128
        return result_tree
 
4129
 
 
4130
    def _do_preview(self, merger):
 
4131
        from bzrlib.diff import show_diff_trees
 
4132
        result_tree = self._get_preview(merger)
 
4133
        path_encoding = osutils.get_diff_header_encoding()
 
4134
        show_diff_trees(merger.this_tree, result_tree, self.outf,
 
4135
                        old_label='', new_label='',
 
4136
                        path_encoding=path_encoding)
 
4137
 
 
4138
    def _do_merge(self, merger, change_reporter, allow_pending, verified):
 
4139
        merger.change_reporter = change_reporter
 
4140
        conflict_count = merger.do_merge()
 
4141
        if allow_pending:
 
4142
            merger.set_pending()
 
4143
        if verified == 'failed':
 
4144
            warning('Preview patch does not match changes')
 
4145
        if conflict_count != 0:
 
4146
            return 1
 
4147
        else:
 
4148
            return 0
 
4149
 
 
4150
    def _do_interactive(self, merger):
 
4151
        """Perform an interactive merge.
 
4152
 
 
4153
        This works by generating a preview tree of the merge, then using
 
4154
        Shelver to selectively remove the differences between the working tree
 
4155
        and the preview tree.
 
4156
        """
 
4157
        from bzrlib import shelf_ui
 
4158
        result_tree = self._get_preview(merger)
 
4159
        writer = bzrlib.option.diff_writer_registry.get()
 
4160
        shelver = shelf_ui.Shelver(merger.this_tree, result_tree, destroy=True,
 
4161
                                   reporter=shelf_ui.ApplyReporter(),
 
4162
                                   diff_writer=writer(sys.stdout))
2504
4163
        try:
2505
 
            try:
2506
 
                conflict_count = _merge_helper(
2507
 
                    other, base, check_clean=(not force),
2508
 
                    merge_type=merge_type,
2509
 
                    reprocess=reprocess,
2510
 
                    show_base=show_base,
2511
 
                    pull=pull,
2512
 
                    this_dir=directory,
2513
 
                    pb=pb, file_list=interesting_files,
2514
 
                    change_reporter=change_reporter)
2515
 
            finally:
2516
 
                pb.finished()
2517
 
            if conflict_count != 0:
2518
 
                return 1
 
4164
            shelver.run()
 
4165
        finally:
 
4166
            shelver.finalize()
 
4167
 
 
4168
    def sanity_check_merger(self, merger):
 
4169
        if (merger.show_base and
 
4170
            not merger.merge_type is _mod_merge.Merge3Merger):
 
4171
            raise errors.BzrCommandError("Show-base is not supported for this"
 
4172
                                         " merge type. %s" % merger.merge_type)
 
4173
        if merger.reprocess is None:
 
4174
            if merger.show_base:
 
4175
                merger.reprocess = False
2519
4176
            else:
2520
 
                return 0
2521
 
        except errors.AmbiguousBase, e:
2522
 
            m = ("sorry, bzr can't determine the right merge base yet\n"
2523
 
                 "candidates are:\n  "
2524
 
                 + "\n  ".join(e.bases)
2525
 
                 + "\n"
2526
 
                 "please specify an explicit base with -r,\n"
2527
 
                 "and (if you want) report this to the bzr developers\n")
2528
 
            log_error(m)
2529
 
 
2530
 
    # TODO: move up to common parent; this isn't merge-specific anymore. 
2531
 
    def _get_remembered_parent(self, tree, supplied_location, verb_string):
 
4177
                # Use reprocess if the merger supports it
 
4178
                merger.reprocess = merger.merge_type.supports_reprocess
 
4179
        if merger.reprocess and not merger.merge_type.supports_reprocess:
 
4180
            raise errors.BzrCommandError("Conflict reduction is not supported"
 
4181
                                         " for merge type %s." %
 
4182
                                         merger.merge_type)
 
4183
        if merger.reprocess and merger.show_base:
 
4184
            raise errors.BzrCommandError("Cannot do conflict reduction and"
 
4185
                                         " show base.")
 
4186
 
 
4187
    def _get_merger_from_branch(self, tree, location, revision, remember,
 
4188
                                possible_transports, pb):
 
4189
        """Produce a merger from a location, assuming it refers to a branch."""
 
4190
        from bzrlib.tag import _merge_tags_if_possible
 
4191
        # find the branch locations
 
4192
        other_loc, user_location = self._select_branch_location(tree, location,
 
4193
            revision, -1)
 
4194
        if revision is not None and len(revision) == 2:
 
4195
            base_loc, _unused = self._select_branch_location(tree,
 
4196
                location, revision, 0)
 
4197
        else:
 
4198
            base_loc = other_loc
 
4199
        # Open the branches
 
4200
        other_branch, other_path = Branch.open_containing(other_loc,
 
4201
            possible_transports)
 
4202
        if base_loc == other_loc:
 
4203
            base_branch = other_branch
 
4204
        else:
 
4205
            base_branch, base_path = Branch.open_containing(base_loc,
 
4206
                possible_transports)
 
4207
        # Find the revision ids
 
4208
        other_revision_id = None
 
4209
        base_revision_id = None
 
4210
        if revision is not None:
 
4211
            if len(revision) >= 1:
 
4212
                other_revision_id = revision[-1].as_revision_id(other_branch)
 
4213
            if len(revision) == 2:
 
4214
                base_revision_id = revision[0].as_revision_id(base_branch)
 
4215
        if other_revision_id is None:
 
4216
            other_revision_id = _mod_revision.ensure_null(
 
4217
                other_branch.last_revision())
 
4218
        # Remember where we merge from. We need to remember if:
 
4219
        # - user specify a location (and we don't merge from the parent
 
4220
        #   branch)
 
4221
        # - user ask to remember or there is no previous location set to merge
 
4222
        #   from and user didn't ask to *not* remember
 
4223
        if (user_location is not None
 
4224
            and ((remember
 
4225
                  or (remember is None
 
4226
                      and tree.branch.get_submit_branch() is None)))):
 
4227
            tree.branch.set_submit_branch(other_branch.base)
 
4228
        # Merge tags (but don't set them in the master branch yet, the user
 
4229
        # might revert this merge).  Commit will propagate them.
 
4230
        _merge_tags_if_possible(other_branch, tree.branch, ignore_master=True)
 
4231
        merger = _mod_merge.Merger.from_revision_ids(pb, tree,
 
4232
            other_revision_id, base_revision_id, other_branch, base_branch)
 
4233
        if other_path != '':
 
4234
            allow_pending = False
 
4235
            merger.interesting_files = [other_path]
 
4236
        else:
 
4237
            allow_pending = True
 
4238
        return merger, allow_pending
 
4239
 
 
4240
    def get_merger_from_uncommitted(self, tree, location, pb):
 
4241
        """Get a merger for uncommitted changes.
 
4242
 
 
4243
        :param tree: The tree the merger should apply to.
 
4244
        :param location: The location containing uncommitted changes.
 
4245
        :param pb: The progress bar to use for showing progress.
 
4246
        """
 
4247
        location = self._select_branch_location(tree, location)[0]
 
4248
        other_tree, other_path = WorkingTree.open_containing(location)
 
4249
        merger = _mod_merge.Merger.from_uncommitted(tree, other_tree, pb)
 
4250
        if other_path != '':
 
4251
            merger.interesting_files = [other_path]
 
4252
        return merger
 
4253
 
 
4254
    def _select_branch_location(self, tree, user_location, revision=None,
 
4255
                                index=None):
 
4256
        """Select a branch location, according to possible inputs.
 
4257
 
 
4258
        If provided, branches from ``revision`` are preferred.  (Both
 
4259
        ``revision`` and ``index`` must be supplied.)
 
4260
 
 
4261
        Otherwise, the ``location`` parameter is used.  If it is None, then the
 
4262
        ``submit`` or ``parent`` location is used, and a note is printed.
 
4263
 
 
4264
        :param tree: The working tree to select a branch for merging into
 
4265
        :param location: The location entered by the user
 
4266
        :param revision: The revision parameter to the command
 
4267
        :param index: The index to use for the revision parameter.  Negative
 
4268
            indices are permitted.
 
4269
        :return: (selected_location, user_location).  The default location
 
4270
            will be the user-entered location.
 
4271
        """
 
4272
        if (revision is not None and index is not None
 
4273
            and revision[index] is not None):
 
4274
            branch = revision[index].get_branch()
 
4275
            if branch is not None:
 
4276
                return branch, branch
 
4277
        if user_location is None:
 
4278
            location = self._get_remembered(tree, 'Merging from')
 
4279
        else:
 
4280
            location = user_location
 
4281
        return location, user_location
 
4282
 
 
4283
    def _get_remembered(self, tree, verb_string):
2532
4284
        """Use tree.branch's parent if none was supplied.
2533
4285
 
2534
4286
        Report if the remembered location was used.
2535
4287
        """
2536
 
        if supplied_location is not None:
2537
 
            return supplied_location
2538
 
        stored_location = tree.branch.get_parent()
 
4288
        stored_location = tree.branch.get_submit_branch()
 
4289
        stored_location_type = "submit"
 
4290
        if stored_location is None:
 
4291
            stored_location = tree.branch.get_parent()
 
4292
            stored_location_type = "parent"
2539
4293
        mutter("%s", stored_location)
2540
4294
        if stored_location is None:
2541
4295
            raise errors.BzrCommandError("No location specified or remembered")
2542
 
        display_url = urlutils.unescape_for_display(stored_location, self.outf.encoding)
2543
 
        self.outf.write("%s remembered location %s\n" % (verb_string, display_url))
 
4296
        display_url = urlutils.unescape_for_display(stored_location, 'utf-8')
 
4297
        note(u"%s remembered %s location %s", verb_string,
 
4298
                stored_location_type, display_url)
2544
4299
        return stored_location
2545
4300
 
2546
4301
 
2547
4302
class cmd_remerge(Command):
2548
 
    """Redo a merge.
 
4303
    __doc__ = """Redo a merge.
2549
4304
 
2550
4305
    Use this if you want to try a different merge technique while resolving
2551
 
    conflicts.  Some merge techniques are better than others, and remerge 
 
4306
    conflicts.  Some merge techniques are better than others, and remerge
2552
4307
    lets you try different ones on different files.
2553
4308
 
2554
4309
    The options for remerge have the same meaning and defaults as the ones for
2555
4310
    merge.  The difference is that remerge can (only) be run when there is a
2556
4311
    pending merge, and it lets you specify particular files.
2557
4312
 
2558
 
    Examples:
2559
 
    $ bzr remerge --show-base
 
4313
    :Examples:
2560
4314
        Re-do the merge of all conflicted files, and show the base text in
2561
 
        conflict regions, in addition to the usual THIS and OTHER texts.
2562
 
 
2563
 
    $ bzr remerge --merge-type weave --reprocess foobar
 
4315
        conflict regions, in addition to the usual THIS and OTHER texts::
 
4316
 
 
4317
            bzr remerge --show-base
 
4318
 
2564
4319
        Re-do the merge of "foobar", using the weave merge algorithm, with
2565
 
        additional processing to reduce the size of conflict regions.
2566
 
    
2567
 
    The following merge types are available:"""
 
4320
        additional processing to reduce the size of conflict regions::
 
4321
 
 
4322
            bzr remerge --merge-type weave --reprocess foobar
 
4323
    """
2568
4324
    takes_args = ['file*']
2569
 
    takes_options = ['merge-type', 'reprocess',
2570
 
                     Option('show-base', help="Show base revision text in "
2571
 
                            "conflicts")]
 
4325
    takes_options = [
 
4326
            'merge-type',
 
4327
            'reprocess',
 
4328
            Option('show-base',
 
4329
                   help="Show base revision text in conflicts."),
 
4330
            ]
2572
4331
 
2573
4332
    def run(self, file_list=None, merge_type=None, show_base=False,
2574
4333
            reprocess=False):
 
4334
        from bzrlib.conflicts import restore
2575
4335
        if merge_type is None:
2576
4336
            merge_type = _mod_merge.Merge3Merger
2577
 
        tree, file_list = tree_files(file_list)
2578
 
        tree.lock_write()
 
4337
        tree, file_list = WorkingTree.open_containing_paths(file_list)
 
4338
        self.add_cleanup(tree.lock_write().unlock)
 
4339
        parents = tree.get_parent_ids()
 
4340
        if len(parents) != 2:
 
4341
            raise errors.BzrCommandError("Sorry, remerge only works after normal"
 
4342
                                         " merges.  Not cherrypicking or"
 
4343
                                         " multi-merges.")
 
4344
        repository = tree.branch.repository
 
4345
        interesting_ids = None
 
4346
        new_conflicts = []
 
4347
        conflicts = tree.conflicts()
 
4348
        if file_list is not None:
 
4349
            interesting_ids = set()
 
4350
            for filename in file_list:
 
4351
                file_id = tree.path2id(filename)
 
4352
                if file_id is None:
 
4353
                    raise errors.NotVersionedError(filename)
 
4354
                interesting_ids.add(file_id)
 
4355
                if tree.kind(file_id) != "directory":
 
4356
                    continue
 
4357
 
 
4358
                for name, ie in tree.inventory.iter_entries(file_id):
 
4359
                    interesting_ids.add(ie.file_id)
 
4360
            new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
 
4361
        else:
 
4362
            # Remerge only supports resolving contents conflicts
 
4363
            allowed_conflicts = ('text conflict', 'contents conflict')
 
4364
            restore_files = [c.path for c in conflicts
 
4365
                             if c.typestring in allowed_conflicts]
 
4366
        _mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
 
4367
        tree.set_conflicts(ConflictList(new_conflicts))
 
4368
        if file_list is not None:
 
4369
            restore_files = file_list
 
4370
        for filename in restore_files:
 
4371
            try:
 
4372
                restore(tree.abspath(filename))
 
4373
            except errors.NotConflicted:
 
4374
                pass
 
4375
        # Disable pending merges, because the file texts we are remerging
 
4376
        # have not had those merges performed.  If we use the wrong parents
 
4377
        # list, we imply that the working tree text has seen and rejected
 
4378
        # all the changes from the other tree, when in fact those changes
 
4379
        # have not yet been seen.
 
4380
        tree.set_parent_ids(parents[:1])
2579
4381
        try:
2580
 
            parents = tree.get_parent_ids()
2581
 
            if len(parents) != 2:
2582
 
                raise errors.BzrCommandError("Sorry, remerge only works after normal"
2583
 
                                             " merges.  Not cherrypicking or"
2584
 
                                             " multi-merges.")
2585
 
            repository = tree.branch.repository
2586
 
            base_revision = common_ancestor(parents[0],
2587
 
                                            parents[1], repository)
2588
 
            base_tree = repository.revision_tree(base_revision)
2589
 
            other_tree = repository.revision_tree(parents[1])
2590
 
            interesting_ids = None
2591
 
            new_conflicts = []
2592
 
            conflicts = tree.conflicts()
2593
 
            if file_list is not None:
2594
 
                interesting_ids = set()
2595
 
                for filename in file_list:
2596
 
                    file_id = tree.path2id(filename)
2597
 
                    if file_id is None:
2598
 
                        raise errors.NotVersionedError(filename)
2599
 
                    interesting_ids.add(file_id)
2600
 
                    if tree.kind(file_id) != "directory":
2601
 
                        continue
2602
 
                    
2603
 
                    for name, ie in tree.inventory.iter_entries(file_id):
2604
 
                        interesting_ids.add(ie.file_id)
2605
 
                new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
2606
 
            else:
2607
 
                # Remerge only supports resolving contents conflicts
2608
 
                allowed_conflicts = ('text conflict', 'contents conflict')
2609
 
                restore_files = [c.path for c in conflicts
2610
 
                                 if c.typestring in allowed_conflicts]
2611
 
            _mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
2612
 
            tree.set_conflicts(ConflictList(new_conflicts))
2613
 
            if file_list is not None:
2614
 
                restore_files = file_list
2615
 
            for filename in restore_files:
2616
 
                try:
2617
 
                    restore(tree.abspath(filename))
2618
 
                except errors.NotConflicted:
2619
 
                    pass
2620
 
            conflicts = _mod_merge.merge_inner(
2621
 
                                      tree.branch, other_tree, base_tree,
2622
 
                                      this_tree=tree,
2623
 
                                      interesting_ids=interesting_ids,
2624
 
                                      other_rev_id=parents[1],
2625
 
                                      merge_type=merge_type,
2626
 
                                      show_base=show_base,
2627
 
                                      reprocess=reprocess)
 
4382
            merger = _mod_merge.Merger.from_revision_ids(None, tree, parents[1])
 
4383
            merger.interesting_ids = interesting_ids
 
4384
            merger.merge_type = merge_type
 
4385
            merger.show_base = show_base
 
4386
            merger.reprocess = reprocess
 
4387
            conflicts = merger.do_merge()
2628
4388
        finally:
2629
 
            tree.unlock()
 
4389
            tree.set_parent_ids(parents)
2630
4390
        if conflicts > 0:
2631
4391
            return 1
2632
4392
        else:
2634
4394
 
2635
4395
 
2636
4396
class cmd_revert(Command):
2637
 
    """Revert files to a previous revision.
 
4397
    __doc__ = """Revert files to a previous revision.
2638
4398
 
2639
4399
    Giving a list of files will revert only those files.  Otherwise, all files
2640
4400
    will be reverted.  If the revision is not specified with '--revision', the
2641
4401
    last committed revision is used.
2642
4402
 
2643
4403
    To remove only some changes, without reverting to a prior version, use
2644
 
    merge instead.  For example, "merge . --r-2..-3" will remove the changes
2645
 
    introduced by -2, without affecting the changes introduced by -1.  Or
2646
 
    to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
2647
 
    
 
4404
    merge instead.  For example, "merge . -r -2..-3" (don't forget the ".")
 
4405
    will remove the changes introduced by the second last commit (-2), without
 
4406
    affecting the changes introduced by the last commit (-1).  To remove
 
4407
    certain changes on a hunk-by-hunk basis, see the shelve command.
 
4408
 
2648
4409
    By default, any files that have been manually changed will be backed up
2649
4410
    first.  (Files changed only by merge are not backed up.)  Backup files have
2650
4411
    '.~#~' appended to their name, where # is a number.
2653
4414
    from the target revision.  So you can use revert to "undelete" a file by
2654
4415
    name.  If you name a directory, all the contents of that directory will be
2655
4416
    reverted.
 
4417
 
 
4418
    If you have newly added files since the target revision, they will be
 
4419
    removed.  If the files to be removed have been changed, backups will be
 
4420
    created as above.  Directories containing unknown files will not be
 
4421
    deleted.
 
4422
 
 
4423
    The working tree contains a list of revisions that have been merged but
 
4424
    not yet committed. These revisions will be included as additional parents
 
4425
    of the next commit.  Normally, using revert clears that list as well as
 
4426
    reverting the files.  If any files are specified, revert leaves the list
 
4427
    of uncommitted merges alone and reverts only the files.  Use ``bzr revert
 
4428
    .`` in the tree root to revert all files but keep the recorded merges,
 
4429
    and ``bzr revert --forget-merges`` to clear the pending merge list without
 
4430
    reverting any files.
 
4431
 
 
4432
    Using "bzr revert --forget-merges", it is possible to apply all of the
 
4433
    changes from a branch in a single revision.  To do this, perform the merge
 
4434
    as desired.  Then doing revert with the "--forget-merges" option will keep
 
4435
    the content of the tree as it was, but it will clear the list of pending
 
4436
    merges.  The next commit will then contain all of the changes that are
 
4437
    present in the other branch, but without any other parent revisions.
 
4438
    Because this technique forgets where these changes originated, it may
 
4439
    cause additional conflicts on later merges involving the same source and
 
4440
    target branches.
2656
4441
    """
2657
 
    takes_options = ['revision', 'no-backup']
 
4442
 
 
4443
    _see_also = ['cat', 'export', 'merge', 'shelve']
 
4444
    takes_options = [
 
4445
        'revision',
 
4446
        Option('no-backup', "Do not save backups of reverted files."),
 
4447
        Option('forget-merges',
 
4448
               'Remove pending merge marker, without changing any files.'),
 
4449
        ]
2658
4450
    takes_args = ['file*']
2659
 
    aliases = ['merge-revert']
2660
 
 
2661
 
    def run(self, revision=None, no_backup=False, file_list=None):
2662
 
        if file_list is not None:
2663
 
            if len(file_list) == 0:
2664
 
                raise errors.BzrCommandError("No files specified")
2665
 
        else:
2666
 
            file_list = []
2667
 
        
2668
 
        tree, file_list = tree_files(file_list)
2669
 
        if revision is None:
2670
 
            # FIXME should be tree.last_revision
2671
 
            rev_id = tree.last_revision()
2672
 
        elif len(revision) != 1:
2673
 
            raise errors.BzrCommandError('bzr revert --revision takes exactly 1 argument')
2674
 
        else:
2675
 
            rev_id = revision[0].in_history(tree.branch).rev_id
2676
 
        pb = ui.ui_factory.nested_progress_bar()
2677
 
        try:
2678
 
            tree.revert(file_list, 
2679
 
                        tree.branch.repository.revision_tree(rev_id),
2680
 
                        not no_backup, pb, report_changes=True)
2681
 
        finally:
2682
 
            pb.finished()
 
4451
 
 
4452
    def run(self, revision=None, no_backup=False, file_list=None,
 
4453
            forget_merges=None):
 
4454
        tree, file_list = WorkingTree.open_containing_paths(file_list)
 
4455
        self.add_cleanup(tree.lock_tree_write().unlock)
 
4456
        if forget_merges:
 
4457
            tree.set_parent_ids(tree.get_parent_ids()[:1])
 
4458
        else:
 
4459
            self._revert_tree_to_revision(tree, revision, file_list, no_backup)
 
4460
 
 
4461
    @staticmethod
 
4462
    def _revert_tree_to_revision(tree, revision, file_list, no_backup):
 
4463
        rev_tree = _get_one_revision_tree('revert', revision, tree=tree)
 
4464
        tree.revert(file_list, rev_tree, not no_backup, None,
 
4465
            report_changes=True)
2683
4466
 
2684
4467
 
2685
4468
class cmd_assert_fail(Command):
2686
 
    """Test reporting of assertion failures"""
 
4469
    __doc__ = """Test reporting of assertion failures"""
2687
4470
    # intended just for use in testing
2688
4471
 
2689
4472
    hidden = True
2693
4476
 
2694
4477
 
2695
4478
class cmd_help(Command):
2696
 
    """Show help on a command or other topic.
 
4479
    __doc__ = """Show help on a command or other topic.
 
4480
    """
2697
4481
 
2698
 
    For a list of all available commands, say 'bzr help commands'.
2699
 
    """
2700
 
    takes_options = [Option('long', 'show help on all commands')]
 
4482
    _see_also = ['topics']
 
4483
    takes_options = [
 
4484
            Option('long', 'Show help on all commands.'),
 
4485
            ]
2701
4486
    takes_args = ['topic?']
2702
4487
    aliases = ['?', '--help', '-?', '-h']
2703
 
    
 
4488
 
2704
4489
    @display_command
2705
4490
    def run(self, topic=None, long=False):
2706
4491
        import bzrlib.help
2710
4495
 
2711
4496
 
2712
4497
class cmd_shell_complete(Command):
2713
 
    """Show appropriate completions for context.
 
4498
    __doc__ = """Show appropriate completions for context.
2714
4499
 
2715
4500
    For a list of all available commands, say 'bzr shell-complete'.
2716
4501
    """
2717
4502
    takes_args = ['context?']
2718
4503
    aliases = ['s-c']
2719
4504
    hidden = True
2720
 
    
 
4505
 
2721
4506
    @display_command
2722
4507
    def run(self, context=None):
2723
4508
        import shellcomplete
2724
4509
        shellcomplete.shellcomplete(context)
2725
4510
 
2726
4511
 
2727
 
class cmd_fetch(Command):
2728
 
    """Copy in history from another branch but don't merge it.
2729
 
 
2730
 
    This is an internal method used for pull and merge.
2731
 
    """
2732
 
    hidden = True
2733
 
    takes_args = ['from_branch', 'to_branch']
2734
 
    def run(self, from_branch, to_branch):
2735
 
        from bzrlib.fetch import Fetcher
2736
 
        from_b = Branch.open(from_branch)
2737
 
        to_b = Branch.open(to_branch)
2738
 
        Fetcher(to_b, from_b)
2739
 
 
2740
 
 
2741
4512
class cmd_missing(Command):
2742
 
    """Show unmerged/unpulled revisions between two branches.
 
4513
    __doc__ = """Show unmerged/unpulled revisions between two branches.
2743
4514
 
2744
4515
    OTHER_BRANCH may be local or remote.
 
4516
 
 
4517
    To filter on a range of revisions, you can use the command -r begin..end
 
4518
    -r revision requests a specific revision, -r ..end or -r begin.. are
 
4519
    also valid.
 
4520
            
 
4521
    :Exit values:
 
4522
        1 - some missing revisions
 
4523
        0 - no missing revisions
 
4524
 
 
4525
    :Examples:
 
4526
 
 
4527
        Determine the missing revisions between this and the branch at the
 
4528
        remembered pull location::
 
4529
 
 
4530
            bzr missing
 
4531
 
 
4532
        Determine the missing revisions between this and another branch::
 
4533
 
 
4534
            bzr missing http://server/branch
 
4535
 
 
4536
        Determine the missing revisions up to a specific revision on the other
 
4537
        branch::
 
4538
 
 
4539
            bzr missing -r ..-10
 
4540
 
 
4541
        Determine the missing revisions up to a specific revision on this
 
4542
        branch::
 
4543
 
 
4544
            bzr missing --my-revision ..-10
2745
4545
    """
 
4546
 
 
4547
    _see_also = ['merge', 'pull']
2746
4548
    takes_args = ['other_branch?']
2747
 
    takes_options = [Option('reverse', 'Reverse the order of revisions'),
2748
 
                     Option('mine-only', 
2749
 
                            'Display changes in the local branch only'),
2750
 
                     Option('theirs-only', 
2751
 
                            'Display changes in the remote branch only'), 
2752
 
                     'log-format',
2753
 
                     'show-ids',
2754
 
                     'verbose'
2755
 
                     ]
 
4549
    takes_options = [
 
4550
        'directory',
 
4551
        Option('reverse', 'Reverse the order of revisions.'),
 
4552
        Option('mine-only',
 
4553
               'Display changes in the local branch only.'),
 
4554
        Option('this' , 'Same as --mine-only.'),
 
4555
        Option('theirs-only',
 
4556
               'Display changes in the remote branch only.'),
 
4557
        Option('other', 'Same as --theirs-only.'),
 
4558
        'log-format',
 
4559
        'show-ids',
 
4560
        'verbose',
 
4561
        custom_help('revision',
 
4562
             help='Filter on other branch revisions (inclusive). '
 
4563
                'See "help revisionspec" for details.'),
 
4564
        Option('my-revision',
 
4565
            type=_parse_revision_str,
 
4566
            help='Filter on local branch revisions (inclusive). '
 
4567
                'See "help revisionspec" for details.'),
 
4568
        Option('include-merges',
 
4569
               'Show all revisions in addition to the mainline ones.'),
 
4570
        ]
2756
4571
    encoding_type = 'replace'
2757
4572
 
2758
4573
    @display_command
2759
4574
    def run(self, other_branch=None, reverse=False, mine_only=False,
2760
 
            theirs_only=False, log_format=None, long=False, short=False, line=False, 
2761
 
            show_ids=False, verbose=False):
2762
 
        from bzrlib.missing import find_unmerged, iter_log_data
2763
 
        from bzrlib.log import log_formatter
2764
 
        local_branch = Branch.open_containing(u".")[0]
 
4575
            theirs_only=False,
 
4576
            log_format=None, long=False, short=False, line=False,
 
4577
            show_ids=False, verbose=False, this=False, other=False,
 
4578
            include_merges=False, revision=None, my_revision=None,
 
4579
            directory=u'.'):
 
4580
        from bzrlib.missing import find_unmerged, iter_log_revisions
 
4581
        def message(s):
 
4582
            if not is_quiet():
 
4583
                self.outf.write(s)
 
4584
 
 
4585
        if this:
 
4586
            mine_only = this
 
4587
        if other:
 
4588
            theirs_only = other
 
4589
        # TODO: We should probably check that we don't have mine-only and
 
4590
        #       theirs-only set, but it gets complicated because we also have
 
4591
        #       this and other which could be used.
 
4592
        restrict = 'all'
 
4593
        if mine_only:
 
4594
            restrict = 'local'
 
4595
        elif theirs_only:
 
4596
            restrict = 'remote'
 
4597
 
 
4598
        local_branch = Branch.open_containing(directory)[0]
 
4599
        self.add_cleanup(local_branch.lock_read().unlock)
 
4600
 
2765
4601
        parent = local_branch.get_parent()
2766
4602
        if other_branch is None:
2767
4603
            other_branch = parent
2768
4604
            if other_branch is None:
2769
 
                raise errors.BzrCommandError("No peer location known or specified.")
 
4605
                raise errors.BzrCommandError("No peer location known"
 
4606
                                             " or specified.")
2770
4607
            display_url = urlutils.unescape_for_display(parent,
2771
4608
                                                        self.outf.encoding)
2772
 
            print "Using last location: " + display_url
 
4609
            message("Using saved parent location: "
 
4610
                    + display_url + "\n")
2773
4611
 
2774
4612
        remote_branch = Branch.open(other_branch)
2775
4613
        if remote_branch.base == local_branch.base:
2776
4614
            remote_branch = local_branch
2777
 
        local_branch.lock_read()
2778
 
        try:
2779
 
            remote_branch.lock_read()
2780
 
            try:
2781
 
                local_extra, remote_extra = find_unmerged(local_branch, remote_branch)
2782
 
                if (log_format is None):
2783
 
                    log_format = log.log_formatter_registry.get_default(
2784
 
                        local_branch)
2785
 
                lf = log_format(to_file=self.outf,
2786
 
                                show_ids=show_ids,
2787
 
                                show_timezone='original')
2788
 
                if reverse is False:
2789
 
                    local_extra.reverse()
2790
 
                    remote_extra.reverse()
2791
 
                if local_extra and not theirs_only:
2792
 
                    print "You have %d extra revision(s):" % len(local_extra)
2793
 
                    for data in iter_log_data(local_extra, local_branch.repository,
2794
 
                                              verbose):
2795
 
                        lf.show(*data)
2796
 
                    printed_local = True
2797
 
                else:
2798
 
                    printed_local = False
2799
 
                if remote_extra and not mine_only:
2800
 
                    if printed_local is True:
2801
 
                        print "\n\n"
2802
 
                    print "You are missing %d revision(s):" % len(remote_extra)
2803
 
                    for data in iter_log_data(remote_extra, remote_branch.repository, 
2804
 
                                              verbose):
2805
 
                        lf.show(*data)
2806
 
                if not remote_extra and not local_extra:
2807
 
                    status_code = 0
2808
 
                    print "Branches are up to date."
2809
 
                else:
2810
 
                    status_code = 1
2811
 
            finally:
2812
 
                remote_branch.unlock()
2813
 
        finally:
2814
 
            local_branch.unlock()
 
4615
        else:
 
4616
            self.add_cleanup(remote_branch.lock_read().unlock)
 
4617
 
 
4618
        local_revid_range = _revision_range_to_revid_range(
 
4619
            _get_revision_range(my_revision, local_branch,
 
4620
                self.name()))
 
4621
 
 
4622
        remote_revid_range = _revision_range_to_revid_range(
 
4623
            _get_revision_range(revision,
 
4624
                remote_branch, self.name()))
 
4625
 
 
4626
        local_extra, remote_extra = find_unmerged(
 
4627
            local_branch, remote_branch, restrict,
 
4628
            backward=not reverse,
 
4629
            include_merges=include_merges,
 
4630
            local_revid_range=local_revid_range,
 
4631
            remote_revid_range=remote_revid_range)
 
4632
 
 
4633
        if log_format is None:
 
4634
            registry = log.log_formatter_registry
 
4635
            log_format = registry.get_default(local_branch)
 
4636
        lf = log_format(to_file=self.outf,
 
4637
                        show_ids=show_ids,
 
4638
                        show_timezone='original')
 
4639
 
 
4640
        status_code = 0
 
4641
        if local_extra and not theirs_only:
 
4642
            message("You have %d extra revision(s):\n" %
 
4643
                len(local_extra))
 
4644
            for revision in iter_log_revisions(local_extra,
 
4645
                                local_branch.repository,
 
4646
                                verbose):
 
4647
                lf.log_revision(revision)
 
4648
            printed_local = True
 
4649
            status_code = 1
 
4650
        else:
 
4651
            printed_local = False
 
4652
 
 
4653
        if remote_extra and not mine_only:
 
4654
            if printed_local is True:
 
4655
                message("\n\n\n")
 
4656
            message("You are missing %d revision(s):\n" %
 
4657
                len(remote_extra))
 
4658
            for revision in iter_log_revisions(remote_extra,
 
4659
                                remote_branch.repository,
 
4660
                                verbose):
 
4661
                lf.log_revision(revision)
 
4662
            status_code = 1
 
4663
 
 
4664
        if mine_only and not local_extra:
 
4665
            # We checked local, and found nothing extra
 
4666
            message('This branch is up to date.\n')
 
4667
        elif theirs_only and not remote_extra:
 
4668
            # We checked remote, and found nothing extra
 
4669
            message('Other branch is up to date.\n')
 
4670
        elif not (mine_only or theirs_only or local_extra or
 
4671
                  remote_extra):
 
4672
            # We checked both branches, and neither one had extra
 
4673
            # revisions
 
4674
            message("Branches are up to date.\n")
 
4675
        self.cleanup_now()
2815
4676
        if not status_code and parent is None and other_branch is not None:
2816
 
            local_branch.lock_write()
2817
 
            try:
2818
 
                # handle race conditions - a parent might be set while we run.
2819
 
                if local_branch.get_parent() is None:
2820
 
                    local_branch.set_parent(remote_branch.base)
2821
 
            finally:
2822
 
                local_branch.unlock()
 
4677
            self.add_cleanup(local_branch.lock_write().unlock)
 
4678
            # handle race conditions - a parent might be set while we run.
 
4679
            if local_branch.get_parent() is None:
 
4680
                local_branch.set_parent(remote_branch.base)
2823
4681
        return status_code
2824
4682
 
2825
4683
 
 
4684
class cmd_pack(Command):
 
4685
    __doc__ = """Compress the data within a repository.
 
4686
 
 
4687
    This operation compresses the data within a bazaar repository. As
 
4688
    bazaar supports automatic packing of repository, this operation is
 
4689
    normally not required to be done manually.
 
4690
 
 
4691
    During the pack operation, bazaar takes a backup of existing repository
 
4692
    data, i.e. pack files. This backup is eventually removed by bazaar
 
4693
    automatically when it is safe to do so. To save disk space by removing
 
4694
    the backed up pack files, the --clean-obsolete-packs option may be
 
4695
    used.
 
4696
 
 
4697
    Warning: If you use --clean-obsolete-packs and your machine crashes
 
4698
    during or immediately after repacking, you may be left with a state
 
4699
    where the deletion has been written to disk but the new packs have not
 
4700
    been. In this case the repository may be unusable.
 
4701
    """
 
4702
 
 
4703
    _see_also = ['repositories']
 
4704
    takes_args = ['branch_or_repo?']
 
4705
    takes_options = [
 
4706
        Option('clean-obsolete-packs', 'Delete obsolete packs to save disk space.'),
 
4707
        ]
 
4708
 
 
4709
    def run(self, branch_or_repo='.', clean_obsolete_packs=False):
 
4710
        dir = bzrdir.BzrDir.open_containing(branch_or_repo)[0]
 
4711
        try:
 
4712
            branch = dir.open_branch()
 
4713
            repository = branch.repository
 
4714
        except errors.NotBranchError:
 
4715
            repository = dir.open_repository()
 
4716
        repository.pack(clean_obsolete_packs=clean_obsolete_packs)
 
4717
 
 
4718
 
2826
4719
class cmd_plugins(Command):
2827
 
    """List plugins"""
2828
 
    hidden = True
 
4720
    __doc__ = """List the installed plugins.
 
4721
 
 
4722
    This command displays the list of installed plugins including
 
4723
    version of plugin and a short description of each.
 
4724
 
 
4725
    --verbose shows the path where each plugin is located.
 
4726
 
 
4727
    A plugin is an external component for Bazaar that extends the
 
4728
    revision control system, by adding or replacing code in Bazaar.
 
4729
    Plugins can do a variety of things, including overriding commands,
 
4730
    adding new commands, providing additional network transports and
 
4731
    customizing log output.
 
4732
 
 
4733
    See the Bazaar Plugin Guide <http://doc.bazaar.canonical.com/plugins/en/>
 
4734
    for further information on plugins including where to find them and how to
 
4735
    install them. Instructions are also provided there on how to write new
 
4736
    plugins using the Python programming language.
 
4737
    """
 
4738
    takes_options = ['verbose']
 
4739
 
2829
4740
    @display_command
2830
 
    def run(self):
2831
 
        import bzrlib.plugin
2832
 
        from inspect import getdoc
2833
 
        for name, plugin in bzrlib.plugin.all_plugins().items():
2834
 
            if getattr(plugin, '__path__', None) is not None:
2835
 
                print plugin.__path__[0]
2836
 
            elif getattr(plugin, '__file__', None) is not None:
2837
 
                print plugin.__file__
2838
 
            else:
2839
 
                print repr(plugin)
2840
 
                
2841
 
            d = getdoc(plugin)
2842
 
            if d:
2843
 
                print '\t', d.split('\n')[0]
 
4741
    def run(self, verbose=False):
 
4742
        from bzrlib import plugin
 
4743
        # Don't give writelines a generator as some codecs don't like that
 
4744
        self.outf.writelines(
 
4745
            list(plugin.describe_plugins(show_paths=verbose)))
2844
4746
 
2845
4747
 
2846
4748
class cmd_testament(Command):
2847
 
    """Show testament (signing-form) of a revision."""
2848
 
    takes_options = ['revision', 
2849
 
                     Option('long', help='Produce long-format testament'), 
2850
 
                     Option('strict', help='Produce a strict-format'
2851
 
                            ' testament')]
 
4749
    __doc__ = """Show testament (signing-form) of a revision."""
 
4750
    takes_options = [
 
4751
            'revision',
 
4752
            Option('long', help='Produce long-format testament.'),
 
4753
            Option('strict',
 
4754
                   help='Produce a strict-format testament.')]
2852
4755
    takes_args = ['branch?']
2853
4756
    @display_command
2854
4757
    def run(self, branch=u'.', revision=None, long=False, strict=False):
2857
4760
            testament_class = StrictTestament
2858
4761
        else:
2859
4762
            testament_class = Testament
2860
 
        b = WorkingTree.open_containing(branch)[0].branch
2861
 
        b.lock_read()
2862
 
        try:
2863
 
            if revision is None:
2864
 
                rev_id = b.last_revision()
2865
 
            else:
2866
 
                rev_id = revision[0].in_history(b).rev_id
2867
 
            t = testament_class.from_revision(b.repository, rev_id)
2868
 
            if long:
2869
 
                sys.stdout.writelines(t.as_text_lines())
2870
 
            else:
2871
 
                sys.stdout.write(t.as_short_text())
2872
 
        finally:
2873
 
            b.unlock()
 
4763
        if branch == '.':
 
4764
            b = Branch.open_containing(branch)[0]
 
4765
        else:
 
4766
            b = Branch.open(branch)
 
4767
        self.add_cleanup(b.lock_read().unlock)
 
4768
        if revision is None:
 
4769
            rev_id = b.last_revision()
 
4770
        else:
 
4771
            rev_id = revision[0].as_revision_id(b)
 
4772
        t = testament_class.from_revision(b.repository, rev_id)
 
4773
        if long:
 
4774
            sys.stdout.writelines(t.as_text_lines())
 
4775
        else:
 
4776
            sys.stdout.write(t.as_short_text())
2874
4777
 
2875
4778
 
2876
4779
class cmd_annotate(Command):
2877
 
    """Show the origin of each line in a file.
 
4780
    __doc__ = """Show the origin of each line in a file.
2878
4781
 
2879
4782
    This prints out the given file with an annotation on the left side
2880
4783
    indicating which revision, author and date introduced the change.
2881
4784
 
2882
 
    If the origin is the same for a run of consecutive lines, it is 
 
4785
    If the origin is the same for a run of consecutive lines, it is
2883
4786
    shown only at the top, unless the --all option is given.
2884
4787
    """
2885
4788
    # TODO: annotate directories; showing when each file was last changed
2886
 
    # TODO: if the working copy is modified, show annotations on that 
 
4789
    # TODO: if the working copy is modified, show annotations on that
2887
4790
    #       with new uncommitted lines marked
2888
4791
    aliases = ['ann', 'blame', 'praise']
2889
4792
    takes_args = ['filename']
2890
 
    takes_options = [Option('all', help='show annotations on all lines'),
2891
 
                     Option('long', help='show date in annotations'),
 
4793
    takes_options = [Option('all', help='Show annotations on all lines.'),
 
4794
                     Option('long', help='Show commit date in annotations.'),
2892
4795
                     'revision',
2893
4796
                     'show-ids',
 
4797
                     'directory',
2894
4798
                     ]
 
4799
    encoding_type = 'exact'
2895
4800
 
2896
4801
    @display_command
2897
4802
    def run(self, filename, all=False, long=False, revision=None,
2898
 
            show_ids=False):
2899
 
        from bzrlib.annotate import annotate_file
2900
 
        tree, relpath = WorkingTree.open_containing(filename)
2901
 
        branch = tree.branch
2902
 
        branch.lock_read()
2903
 
        try:
2904
 
            if revision is None:
2905
 
                revision_id = branch.last_revision()
2906
 
            elif len(revision) != 1:
2907
 
                raise errors.BzrCommandError('bzr annotate --revision takes exactly 1 argument')
2908
 
            else:
2909
 
                revision_id = revision[0].in_history(branch).rev_id
2910
 
            file_id = tree.inventory.path2id(relpath)
2911
 
            tree = branch.repository.revision_tree(revision_id)
2912
 
            file_version = tree.inventory[file_id].revision
2913
 
            annotate_file(branch, file_version, file_id, long, all, sys.stdout,
2914
 
                          show_ids=show_ids)
2915
 
        finally:
2916
 
            branch.unlock()
 
4803
            show_ids=False, directory=None):
 
4804
        from bzrlib.annotate import (
 
4805
            annotate_file_tree,
 
4806
            )
 
4807
        wt, branch, relpath = \
 
4808
            _open_directory_or_containing_tree_or_branch(filename, directory)
 
4809
        if wt is not None:
 
4810
            self.add_cleanup(wt.lock_read().unlock)
 
4811
        else:
 
4812
            self.add_cleanup(branch.lock_read().unlock)
 
4813
        tree = _get_one_revision_tree('annotate', revision, branch=branch)
 
4814
        self.add_cleanup(tree.lock_read().unlock)
 
4815
        if wt is not None and revision is None:
 
4816
            file_id = wt.path2id(relpath)
 
4817
        else:
 
4818
            file_id = tree.path2id(relpath)
 
4819
        if file_id is None:
 
4820
            raise errors.NotVersionedError(filename)
 
4821
        if wt is not None and revision is None:
 
4822
            # If there is a tree and we're not annotating historical
 
4823
            # versions, annotate the working tree's content.
 
4824
            annotate_file_tree(wt, file_id, self.outf, long, all,
 
4825
                show_ids=show_ids)
 
4826
        else:
 
4827
            annotate_file_tree(tree, file_id, self.outf, long, all,
 
4828
                show_ids=show_ids, branch=branch)
2917
4829
 
2918
4830
 
2919
4831
class cmd_re_sign(Command):
2920
 
    """Create a digital signature for an existing revision."""
 
4832
    __doc__ = """Create a digital signature for an existing revision."""
2921
4833
    # TODO be able to replace existing ones.
2922
4834
 
2923
4835
    hidden = True # is this right ?
2924
4836
    takes_args = ['revision_id*']
2925
 
    takes_options = ['revision']
2926
 
    
2927
 
    def run(self, revision_id_list=None, revision=None):
2928
 
        import bzrlib.gpg as gpg
 
4837
    takes_options = ['directory', 'revision']
 
4838
 
 
4839
    def run(self, revision_id_list=None, revision=None, directory=u'.'):
2929
4840
        if revision_id_list is not None and revision is not None:
2930
4841
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
2931
4842
        if revision_id_list is None and revision is None:
2932
4843
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
2933
 
        b = WorkingTree.open_containing(u'.')[0].branch
 
4844
        b = WorkingTree.open_containing(directory)[0].branch
 
4845
        self.add_cleanup(b.lock_write().unlock)
 
4846
        return self._run(b, revision_id_list, revision)
 
4847
 
 
4848
    def _run(self, b, revision_id_list, revision):
 
4849
        import bzrlib.gpg as gpg
2934
4850
        gpg_strategy = gpg.GPGStrategy(b.get_config())
2935
4851
        if revision_id_list is not None:
2936
 
            for revision_id in revision_id_list:
2937
 
                b.repository.sign_revision(revision_id, gpg_strategy)
 
4852
            b.repository.start_write_group()
 
4853
            try:
 
4854
                for revision_id in revision_id_list:
 
4855
                    b.repository.sign_revision(revision_id, gpg_strategy)
 
4856
            except:
 
4857
                b.repository.abort_write_group()
 
4858
                raise
 
4859
            else:
 
4860
                b.repository.commit_write_group()
2938
4861
        elif revision is not None:
2939
4862
            if len(revision) == 1:
2940
4863
                revno, rev_id = revision[0].in_history(b)
2941
 
                b.repository.sign_revision(rev_id, gpg_strategy)
 
4864
                b.repository.start_write_group()
 
4865
                try:
 
4866
                    b.repository.sign_revision(rev_id, gpg_strategy)
 
4867
                except:
 
4868
                    b.repository.abort_write_group()
 
4869
                    raise
 
4870
                else:
 
4871
                    b.repository.commit_write_group()
2942
4872
            elif len(revision) == 2:
2943
4873
                # are they both on rh- if so we can walk between them
2944
4874
                # might be nice to have a range helper for arbitrary
2949
4879
                    to_revno = b.revno()
2950
4880
                if from_revno is None or to_revno is None:
2951
4881
                    raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
2952
 
                for revno in range(from_revno, to_revno + 1):
2953
 
                    b.repository.sign_revision(b.get_rev_id(revno), 
2954
 
                                               gpg_strategy)
 
4882
                b.repository.start_write_group()
 
4883
                try:
 
4884
                    for revno in range(from_revno, to_revno + 1):
 
4885
                        b.repository.sign_revision(b.get_rev_id(revno),
 
4886
                                                   gpg_strategy)
 
4887
                except:
 
4888
                    b.repository.abort_write_group()
 
4889
                    raise
 
4890
                else:
 
4891
                    b.repository.commit_write_group()
2955
4892
            else:
2956
4893
                raise errors.BzrCommandError('Please supply either one revision, or a range.')
2957
4894
 
2958
4895
 
2959
4896
class cmd_bind(Command):
2960
 
    """Convert the current branch into a checkout of the supplied branch.
 
4897
    __doc__ = """Convert the current branch into a checkout of the supplied branch.
 
4898
    If no branch is supplied, rebind to the last bound location.
2961
4899
 
2962
4900
    Once converted into a checkout, commits must succeed on the master branch
2963
4901
    before they will be applied to the local branch.
2964
4902
 
2965
 
    See "help checkouts" for more information on checkouts.
 
4903
    Bound branches use the nickname of its master branch unless it is set
 
4904
    locally, in which case binding will update the local nickname to be
 
4905
    that of the master.
2966
4906
    """
2967
4907
 
 
4908
    _see_also = ['checkouts', 'unbind']
2968
4909
    takes_args = ['location?']
2969
 
    takes_options = []
 
4910
    takes_options = ['directory']
2970
4911
 
2971
 
    def run(self, location=None):
2972
 
        b, relpath = Branch.open_containing(u'.')
 
4912
    def run(self, location=None, directory=u'.'):
 
4913
        b, relpath = Branch.open_containing(directory)
2973
4914
        if location is None:
2974
4915
            try:
2975
4916
                location = b.get_old_bound_location()
2978
4919
                    'This format does not remember old locations.')
2979
4920
            else:
2980
4921
                if location is None:
2981
 
                    raise errors.BzrCommandError('No location supplied and no '
2982
 
                        'previous location known')
 
4922
                    if b.get_bound_location() is not None:
 
4923
                        raise errors.BzrCommandError('Branch is already bound')
 
4924
                    else:
 
4925
                        raise errors.BzrCommandError('No location supplied '
 
4926
                            'and no previous location known')
2983
4927
        b_other = Branch.open(location)
2984
4928
        try:
2985
4929
            b.bind(b_other)
2986
4930
        except errors.DivergedBranches:
2987
4931
            raise errors.BzrCommandError('These branches have diverged.'
2988
4932
                                         ' Try merging, and then bind again.')
 
4933
        if b.get_config().has_explicit_nickname():
 
4934
            b.nick = b_other.nick
2989
4935
 
2990
4936
 
2991
4937
class cmd_unbind(Command):
2992
 
    """Convert the current checkout into a regular branch.
 
4938
    __doc__ = """Convert the current checkout into a regular branch.
2993
4939
 
2994
4940
    After unbinding, the local branch is considered independent and subsequent
2995
4941
    commits will be local only.
2996
 
 
2997
 
    See "help checkouts" for more information on checkouts.
2998
4942
    """
2999
4943
 
 
4944
    _see_also = ['checkouts', 'bind']
3000
4945
    takes_args = []
3001
 
    takes_options = []
 
4946
    takes_options = ['directory']
3002
4947
 
3003
 
    def run(self):
3004
 
        b, relpath = Branch.open_containing(u'.')
 
4948
    def run(self, directory=u'.'):
 
4949
        b, relpath = Branch.open_containing(directory)
3005
4950
        if not b.unbind():
3006
4951
            raise errors.BzrCommandError('Local branch is not bound')
3007
4952
 
3008
4953
 
3009
4954
class cmd_uncommit(Command):
3010
 
    """Remove the last committed revision.
 
4955
    __doc__ = """Remove the last committed revision.
3011
4956
 
3012
4957
    --verbose will print out what is being removed.
3013
4958
    --dry-run will go through all the motions, but not actually
3014
4959
    remove anything.
3015
 
    
3016
 
    In the future, uncommit will create a revision bundle, which can then
3017
 
    be re-applied.
 
4960
 
 
4961
    If --revision is specified, uncommit revisions to leave the branch at the
 
4962
    specified revision.  For example, "bzr uncommit -r 15" will leave the
 
4963
    branch at revision 15.
 
4964
 
 
4965
    Uncommit leaves the working tree ready for a new commit.  The only change
 
4966
    it may make is to restore any pending merges that were present before
 
4967
    the commit.
3018
4968
    """
3019
4969
 
3020
4970
    # TODO: jam 20060108 Add an option to allow uncommit to remove
3021
4971
    # unreferenced information in 'branch-as-repository' branches.
3022
4972
    # TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
3023
4973
    # information in shared branches as well.
 
4974
    _see_also = ['commit']
3024
4975
    takes_options = ['verbose', 'revision',
3025
 
                    Option('dry-run', help='Don\'t actually make changes'),
3026
 
                    Option('force', help='Say yes to all questions.')]
 
4976
                    Option('dry-run', help='Don\'t actually make changes.'),
 
4977
                    Option('force', help='Say yes to all questions.'),
 
4978
                    Option('local',
 
4979
                           help="Only remove the commits from the local branch"
 
4980
                                " when in a checkout."
 
4981
                           ),
 
4982
                    ]
3027
4983
    takes_args = ['location?']
3028
4984
    aliases = []
 
4985
    encoding_type = 'replace'
3029
4986
 
3030
4987
    def run(self, location=None,
3031
4988
            dry_run=False, verbose=False,
3032
 
            revision=None, force=False):
 
4989
            revision=None, force=False, local=False):
 
4990
        if location is None:
 
4991
            location = u'.'
 
4992
        control, relpath = bzrdir.BzrDir.open_containing(location)
 
4993
        try:
 
4994
            tree = control.open_workingtree()
 
4995
            b = tree.branch
 
4996
        except (errors.NoWorkingTree, errors.NotLocalUrl):
 
4997
            tree = None
 
4998
            b = control.open_branch()
 
4999
 
 
5000
        if tree is not None:
 
5001
            self.add_cleanup(tree.lock_write().unlock)
 
5002
        else:
 
5003
            self.add_cleanup(b.lock_write().unlock)
 
5004
        return self._run(b, tree, dry_run, verbose, revision, force, local=local)
 
5005
 
 
5006
    def _run(self, b, tree, dry_run, verbose, revision, force, local=False):
3033
5007
        from bzrlib.log import log_formatter, show_log
3034
 
        import sys
3035
5008
        from bzrlib.uncommit import uncommit
3036
5009
 
3037
 
        if location is None:
3038
 
            location = u'.'
3039
 
        control, relpath = bzrdir.BzrDir.open_containing(location)
3040
 
        try:
3041
 
            tree = control.open_workingtree()
3042
 
            b = tree.branch
3043
 
        except (errors.NoWorkingTree, errors.NotLocalUrl):
3044
 
            tree = None
3045
 
            b = control.open_branch()
 
5010
        last_revno, last_rev_id = b.last_revision_info()
3046
5011
 
3047
5012
        rev_id = None
3048
5013
        if revision is None:
3049
 
            revno = b.revno()
 
5014
            revno = last_revno
 
5015
            rev_id = last_rev_id
3050
5016
        else:
3051
5017
            # 'bzr uncommit -r 10' actually means uncommit
3052
5018
            # so that the final tree is at revno 10.
3053
5019
            # but bzrlib.uncommit.uncommit() actually uncommits
3054
5020
            # the revisions that are supplied.
3055
5021
            # So we need to offset it by one
3056
 
            revno = revision[0].in_history(b).revno+1
 
5022
            revno = revision[0].in_history(b).revno + 1
 
5023
            if revno <= last_revno:
 
5024
                rev_id = b.get_rev_id(revno)
3057
5025
 
3058
 
        if revno <= b.revno():
3059
 
            rev_id = b.get_rev_id(revno)
3060
 
        if rev_id is None:
 
5026
        if rev_id is None or _mod_revision.is_null(rev_id):
3061
5027
            self.outf.write('No revisions to uncommit.\n')
3062
5028
            return 1
3063
5029
 
3070
5036
                 verbose=False,
3071
5037
                 direction='forward',
3072
5038
                 start_revision=revno,
3073
 
                 end_revision=b.revno())
 
5039
                 end_revision=last_revno)
3074
5040
 
3075
5041
        if dry_run:
3076
 
            print 'Dry-run, pretending to remove the above revisions.'
3077
 
            if not force:
3078
 
                val = raw_input('Press <enter> to continue')
 
5042
            self.outf.write('Dry-run, pretending to remove'
 
5043
                            ' the above revisions.\n')
3079
5044
        else:
3080
 
            print 'The above revision(s) will be removed.'
3081
 
            if not force:
3082
 
                val = raw_input('Are you sure [y/N]? ')
3083
 
                if val.lower() not in ('y', 'yes'):
3084
 
                    print 'Canceled'
3085
 
                    return 0
3086
 
 
 
5045
            self.outf.write('The above revision(s) will be removed.\n')
 
5046
 
 
5047
        if not force:
 
5048
            if not ui.ui_factory.confirm_action(
 
5049
                    u'Uncommit these revisions',
 
5050
                    'bzrlib.builtins.uncommit',
 
5051
                    {}):
 
5052
                self.outf.write('Canceled\n')
 
5053
                return 0
 
5054
 
 
5055
        mutter('Uncommitting from {%s} to {%s}',
 
5056
               last_rev_id, rev_id)
3087
5057
        uncommit(b, tree=tree, dry_run=dry_run, verbose=verbose,
3088
 
                revno=revno)
 
5058
                 revno=revno, local=local)
 
5059
        self.outf.write('You can restore the old tip by running:\n'
 
5060
             '  bzr pull . -r revid:%s\n' % last_rev_id)
3089
5061
 
3090
5062
 
3091
5063
class cmd_break_lock(Command):
3092
 
    """Break a dead lock on a repository, branch or working directory.
 
5064
    __doc__ = """Break a dead lock.
 
5065
 
 
5066
    This command breaks a lock on a repository, branch, working directory or
 
5067
    config file.
3093
5068
 
3094
5069
    CAUTION: Locks should only be broken when you are sure that the process
3095
5070
    holding the lock has been stopped.
3096
5071
 
3097
 
    You can get information on what locks are open via the 'bzr info' command.
3098
 
    
3099
 
    example:
 
5072
    You can get information on what locks are open via the 'bzr info
 
5073
    [location]' command.
 
5074
 
 
5075
    :Examples:
3100
5076
        bzr break-lock
 
5077
        bzr break-lock bzr+ssh://example.com/bzr/foo
 
5078
        bzr break-lock --conf ~/.bazaar
3101
5079
    """
 
5080
 
3102
5081
    takes_args = ['location?']
 
5082
    takes_options = [
 
5083
        Option('config',
 
5084
               help='LOCATION is the directory where the config lock is.'),
 
5085
        Option('force',
 
5086
            help='Do not ask for confirmation before breaking the lock.'),
 
5087
        ]
3103
5088
 
3104
 
    def run(self, location=None, show=False):
 
5089
    def run(self, location=None, config=False, force=False):
3105
5090
        if location is None:
3106
5091
            location = u'.'
3107
 
        control, relpath = bzrdir.BzrDir.open_containing(location)
3108
 
        try:
3109
 
            control.break_lock()
3110
 
        except NotImplementedError:
3111
 
            pass
3112
 
        
 
5092
        if force:
 
5093
            ui.ui_factory = ui.ConfirmationUserInterfacePolicy(ui.ui_factory,
 
5094
                None,
 
5095
                {'bzrlib.lockdir.break': True})
 
5096
        if config:
 
5097
            conf = _mod_config.LockableConfig(file_name=location)
 
5098
            conf.break_lock()
 
5099
        else:
 
5100
            control, relpath = bzrdir.BzrDir.open_containing(location)
 
5101
            try:
 
5102
                control.break_lock()
 
5103
            except NotImplementedError:
 
5104
                pass
 
5105
 
3113
5106
 
3114
5107
class cmd_wait_until_signalled(Command):
3115
 
    """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
 
5108
    __doc__ = """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
3116
5109
 
3117
5110
    This just prints a line to signal when it is ready, then blocks on stdin.
3118
5111
    """
3126
5119
 
3127
5120
 
3128
5121
class cmd_serve(Command):
3129
 
    """Run the bzr server."""
 
5122
    __doc__ = """Run the bzr server."""
3130
5123
 
3131
5124
    aliases = ['server']
3132
5125
 
3133
5126
    takes_options = [
3134
5127
        Option('inet',
3135
 
               help='serve on stdin/out for use from inetd or sshd'),
 
5128
               help='Serve on stdin/out for use from inetd or sshd.'),
 
5129
        RegistryOption('protocol',
 
5130
               help="Protocol to serve.",
 
5131
               lazy_registry=('bzrlib.transport', 'transport_server_registry'),
 
5132
               value_switches=True),
3136
5133
        Option('port',
3137
 
               help='listen for connections on nominated port of the form '
3138
 
                    '[hostname:]portnumber. Passing 0 as the port number will '
3139
 
                    'result in a dynamically allocated port.',
 
5134
               help='Listen for connections on nominated port of the form '
 
5135
                    '[hostname:]portnumber.  Passing 0 as the port number will '
 
5136
                    'result in a dynamically allocated port.  The default port '
 
5137
                    'depends on the protocol.',
3140
5138
               type=str),
3141
 
        Option('directory',
3142
 
               help='serve contents of directory',
3143
 
               type=unicode),
 
5139
        custom_help('directory',
 
5140
               help='Serve contents of this directory.'),
3144
5141
        Option('allow-writes',
3145
 
               help='By default the server is a readonly server. Supplying '
 
5142
               help='By default the server is a readonly server.  Supplying '
3146
5143
                    '--allow-writes enables write access to the contents of '
3147
 
                    'the served directory and below. '
 
5144
                    'the served directory and below.  Note that ``bzr serve`` '
 
5145
                    'does not perform authentication, so unless some form of '
 
5146
                    'external authentication is arranged supplying this '
 
5147
                    'option leads to global uncontrolled write access to your '
 
5148
                    'file system.'
3148
5149
                ),
3149
5150
        ]
3150
5151
 
3151
 
    def run(self, port=None, inet=False, directory=None, allow_writes=False):
3152
 
        from bzrlib.transport import smart
3153
 
        from bzrlib.transport import get_transport
 
5152
    def get_host_and_port(self, port):
 
5153
        """Return the host and port to run the smart server on.
 
5154
 
 
5155
        If 'port' is None, None will be returned for the host and port.
 
5156
 
 
5157
        If 'port' has a colon in it, the string before the colon will be
 
5158
        interpreted as the host.
 
5159
 
 
5160
        :param port: A string of the port to run the server on.
 
5161
        :return: A tuple of (host, port), where 'host' is a host name or IP,
 
5162
            and port is an integer TCP/IP port.
 
5163
        """
 
5164
        host = None
 
5165
        if port is not None:
 
5166
            if ':' in port:
 
5167
                host, port = port.split(':')
 
5168
            port = int(port)
 
5169
        return host, port
 
5170
 
 
5171
    def run(self, port=None, inet=False, directory=None, allow_writes=False,
 
5172
            protocol=None):
 
5173
        from bzrlib import transport
3154
5174
        if directory is None:
3155
5175
            directory = os.getcwd()
 
5176
        if protocol is None:
 
5177
            protocol = transport.transport_server_registry.get()
 
5178
        host, port = self.get_host_and_port(port)
3156
5179
        url = urlutils.local_path_to_url(directory)
3157
5180
        if not allow_writes:
3158
5181
            url = 'readonly+' + url
3159
 
        t = get_transport(url)
3160
 
        if inet:
3161
 
            server = smart.SmartServerPipeStreamMedium(sys.stdin, sys.stdout, t)
3162
 
        elif port is not None:
3163
 
            if ':' in port:
3164
 
                host, port = port.split(':')
3165
 
            else:
3166
 
                host = '127.0.0.1'
3167
 
            server = smart.SmartTCPServer(t, host=host, port=int(port))
3168
 
            print 'listening on port: ', server.port
3169
 
            sys.stdout.flush()
3170
 
        else:
3171
 
            raise errors.BzrCommandError("bzr serve requires one of --inet or --port")
3172
 
        server.serve()
3173
 
 
3174
 
 
3175
 
# command-line interpretation helper for merge-related commands
3176
 
def _merge_helper(other_revision, base_revision,
3177
 
                  check_clean=True, ignore_zero=False,
3178
 
                  this_dir=None, backup_files=False,
3179
 
                  merge_type=None,
3180
 
                  file_list=None, show_base=False, reprocess=False,
3181
 
                  pull=False,
3182
 
                  pb=DummyProgress(),
3183
 
                  change_reporter=None):
3184
 
    """Merge changes into a tree.
3185
 
 
3186
 
    base_revision
3187
 
        list(path, revno) Base for three-way merge.  
3188
 
        If [None, None] then a base will be automatically determined.
3189
 
    other_revision
3190
 
        list(path, revno) Other revision for three-way merge.
3191
 
    this_dir
3192
 
        Directory to merge changes into; '.' by default.
3193
 
    check_clean
3194
 
        If true, this_dir must have no uncommitted changes before the
3195
 
        merge begins.
3196
 
    ignore_zero - If true, suppress the "zero conflicts" message when 
3197
 
        there are no conflicts; should be set when doing something we expect
3198
 
        to complete perfectly.
3199
 
    file_list - If supplied, merge only changes to selected files.
3200
 
 
3201
 
    All available ancestors of other_revision and base_revision are
3202
 
    automatically pulled into the branch.
3203
 
 
3204
 
    The revno may be -1 to indicate the last revision on the branch, which is
3205
 
    the typical case.
3206
 
 
3207
 
    This function is intended for use from the command line; programmatic
3208
 
    clients might prefer to call merge.merge_inner(), which has less magic 
3209
 
    behavior.
3210
 
    """
3211
 
    # Loading it late, so that we don't always have to import bzrlib.merge
3212
 
    if merge_type is None:
3213
 
        merge_type = _mod_merge.Merge3Merger
3214
 
    if this_dir is None:
3215
 
        this_dir = u'.'
3216
 
    this_tree = WorkingTree.open_containing(this_dir)[0]
3217
 
    if show_base and not merge_type is _mod_merge.Merge3Merger:
3218
 
        raise errors.BzrCommandError("Show-base is not supported for this merge"
3219
 
                                     " type. %s" % merge_type)
3220
 
    if reprocess and not merge_type.supports_reprocess:
3221
 
        raise errors.BzrCommandError("Conflict reduction is not supported for merge"
3222
 
                                     " type %s." % merge_type)
3223
 
    if reprocess and show_base:
3224
 
        raise errors.BzrCommandError("Cannot do conflict reduction and show base.")
3225
 
    try:
3226
 
        merger = _mod_merge.Merger(this_tree.branch, this_tree=this_tree,
3227
 
                                   pb=pb, change_reporter=change_reporter)
3228
 
        merger.pp = ProgressPhase("Merge phase", 5, pb)
3229
 
        merger.pp.next_phase()
3230
 
        merger.check_basis(check_clean)
3231
 
        merger.set_other(other_revision)
3232
 
        merger.pp.next_phase()
3233
 
        merger.set_base(base_revision)
3234
 
        if merger.base_rev_id == merger.other_rev_id:
3235
 
            note('Nothing to do.')
3236
 
            return 0
3237
 
        if file_list is None:
3238
 
            if pull and merger.base_rev_id == merger.this_rev_id:
3239
 
                count = merger.this_tree.pull(merger.this_branch,
3240
 
                        False, merger.other_rev_id)
3241
 
                note('%d revision(s) pulled.' % (count,))
3242
 
                return 0
3243
 
        merger.backup_files = backup_files
3244
 
        merger.merge_type = merge_type 
3245
 
        merger.set_interesting_files(file_list)
3246
 
        merger.show_base = show_base 
3247
 
        merger.reprocess = reprocess
3248
 
        conflicts = merger.do_merge()
3249
 
        if file_list is None:
3250
 
            merger.set_pending()
3251
 
    finally:
3252
 
        pb.clear()
3253
 
    return conflicts
3254
 
 
3255
 
 
3256
 
# Compatibility
3257
 
merge = _merge_helper
3258
 
 
3259
 
 
3260
 
# these get imported and then picked up by the scan for cmd_*
3261
 
# TODO: Some more consistent way to split command definitions across files;
3262
 
# we do need to load at least some information about them to know of 
3263
 
# aliases.  ideally we would avoid loading the implementation until the
3264
 
# details were needed.
3265
 
from bzrlib.cmd_version_info import cmd_version_info
3266
 
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
3267
 
from bzrlib.bundle.commands import cmd_bundle_revisions
3268
 
from bzrlib.sign_my_commits import cmd_sign_my_commits
3269
 
from bzrlib.weave_commands import cmd_weave_list, cmd_weave_join, \
3270
 
        cmd_weave_plan_merge, cmd_weave_merge_text
 
5182
        t = transport.get_transport(url)
 
5183
        protocol(t, host, port, inet)
 
5184
 
 
5185
 
 
5186
class cmd_join(Command):
 
5187
    __doc__ = """Combine a tree into its containing tree.
 
5188
 
 
5189
    This command requires the target tree to be in a rich-root format.
 
5190
 
 
5191
    The TREE argument should be an independent tree, inside another tree, but
 
5192
    not part of it.  (Such trees can be produced by "bzr split", but also by
 
5193
    running "bzr branch" with the target inside a tree.)
 
5194
 
 
5195
    The result is a combined tree, with the subtree no longer an independent
 
5196
    part.  This is marked as a merge of the subtree into the containing tree,
 
5197
    and all history is preserved.
 
5198
    """
 
5199
 
 
5200
    _see_also = ['split']
 
5201
    takes_args = ['tree']
 
5202
    takes_options = [
 
5203
            Option('reference', help='Join by reference.', hidden=True),
 
5204
            ]
 
5205
 
 
5206
    def run(self, tree, reference=False):
 
5207
        sub_tree = WorkingTree.open(tree)
 
5208
        parent_dir = osutils.dirname(sub_tree.basedir)
 
5209
        containing_tree = WorkingTree.open_containing(parent_dir)[0]
 
5210
        repo = containing_tree.branch.repository
 
5211
        if not repo.supports_rich_root():
 
5212
            raise errors.BzrCommandError(
 
5213
                "Can't join trees because %s doesn't support rich root data.\n"
 
5214
                "You can use bzr upgrade on the repository."
 
5215
                % (repo,))
 
5216
        if reference:
 
5217
            try:
 
5218
                containing_tree.add_reference(sub_tree)
 
5219
            except errors.BadReferenceTarget, e:
 
5220
                # XXX: Would be better to just raise a nicely printable
 
5221
                # exception from the real origin.  Also below.  mbp 20070306
 
5222
                raise errors.BzrCommandError("Cannot join %s.  %s" %
 
5223
                                             (tree, e.reason))
 
5224
        else:
 
5225
            try:
 
5226
                containing_tree.subsume(sub_tree)
 
5227
            except errors.BadSubsumeSource, e:
 
5228
                raise errors.BzrCommandError("Cannot join %s.  %s" %
 
5229
                                             (tree, e.reason))
 
5230
 
 
5231
 
 
5232
class cmd_split(Command):
 
5233
    __doc__ = """Split a subdirectory of a tree into a separate tree.
 
5234
 
 
5235
    This command will produce a target tree in a format that supports
 
5236
    rich roots, like 'rich-root' or 'rich-root-pack'.  These formats cannot be
 
5237
    converted into earlier formats like 'dirstate-tags'.
 
5238
 
 
5239
    The TREE argument should be a subdirectory of a working tree.  That
 
5240
    subdirectory will be converted into an independent tree, with its own
 
5241
    branch.  Commits in the top-level tree will not apply to the new subtree.
 
5242
    """
 
5243
 
 
5244
    _see_also = ['join']
 
5245
    takes_args = ['tree']
 
5246
 
 
5247
    def run(self, tree):
 
5248
        containing_tree, subdir = WorkingTree.open_containing(tree)
 
5249
        sub_id = containing_tree.path2id(subdir)
 
5250
        if sub_id is None:
 
5251
            raise errors.NotVersionedError(subdir)
 
5252
        try:
 
5253
            containing_tree.extract(sub_id)
 
5254
        except errors.RootNotRich:
 
5255
            raise errors.RichRootUpgradeRequired(containing_tree.branch.base)
 
5256
 
 
5257
 
 
5258
class cmd_merge_directive(Command):
 
5259
    __doc__ = """Generate a merge directive for auto-merge tools.
 
5260
 
 
5261
    A directive requests a merge to be performed, and also provides all the
 
5262
    information necessary to do so.  This means it must either include a
 
5263
    revision bundle, or the location of a branch containing the desired
 
5264
    revision.
 
5265
 
 
5266
    A submit branch (the location to merge into) must be supplied the first
 
5267
    time the command is issued.  After it has been supplied once, it will
 
5268
    be remembered as the default.
 
5269
 
 
5270
    A public branch is optional if a revision bundle is supplied, but required
 
5271
    if --diff or --plain is specified.  It will be remembered as the default
 
5272
    after the first use.
 
5273
    """
 
5274
 
 
5275
    takes_args = ['submit_branch?', 'public_branch?']
 
5276
 
 
5277
    hidden = True
 
5278
 
 
5279
    _see_also = ['send']
 
5280
 
 
5281
    takes_options = [
 
5282
        'directory',
 
5283
        RegistryOption.from_kwargs('patch-type',
 
5284
            'The type of patch to include in the directive.',
 
5285
            title='Patch type',
 
5286
            value_switches=True,
 
5287
            enum_switch=False,
 
5288
            bundle='Bazaar revision bundle (default).',
 
5289
            diff='Normal unified diff.',
 
5290
            plain='No patch, just directive.'),
 
5291
        Option('sign', help='GPG-sign the directive.'), 'revision',
 
5292
        Option('mail-to', type=str,
 
5293
            help='Instead of printing the directive, email to this address.'),
 
5294
        Option('message', type=str, short_name='m',
 
5295
            help='Message to use when committing this merge.')
 
5296
        ]
 
5297
 
 
5298
    encoding_type = 'exact'
 
5299
 
 
5300
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
 
5301
            sign=False, revision=None, mail_to=None, message=None,
 
5302
            directory=u'.'):
 
5303
        from bzrlib.revision import ensure_null, NULL_REVISION
 
5304
        include_patch, include_bundle = {
 
5305
            'plain': (False, False),
 
5306
            'diff': (True, False),
 
5307
            'bundle': (True, True),
 
5308
            }[patch_type]
 
5309
        branch = Branch.open(directory)
 
5310
        stored_submit_branch = branch.get_submit_branch()
 
5311
        if submit_branch is None:
 
5312
            submit_branch = stored_submit_branch
 
5313
        else:
 
5314
            if stored_submit_branch is None:
 
5315
                branch.set_submit_branch(submit_branch)
 
5316
        if submit_branch is None:
 
5317
            submit_branch = branch.get_parent()
 
5318
        if submit_branch is None:
 
5319
            raise errors.BzrCommandError('No submit branch specified or known')
 
5320
 
 
5321
        stored_public_branch = branch.get_public_branch()
 
5322
        if public_branch is None:
 
5323
            public_branch = stored_public_branch
 
5324
        elif stored_public_branch is None:
 
5325
            branch.set_public_branch(public_branch)
 
5326
        if not include_bundle and public_branch is None:
 
5327
            raise errors.BzrCommandError('No public branch specified or'
 
5328
                                         ' known')
 
5329
        base_revision_id = None
 
5330
        if revision is not None:
 
5331
            if len(revision) > 2:
 
5332
                raise errors.BzrCommandError('bzr merge-directive takes '
 
5333
                    'at most two one revision identifiers')
 
5334
            revision_id = revision[-1].as_revision_id(branch)
 
5335
            if len(revision) == 2:
 
5336
                base_revision_id = revision[0].as_revision_id(branch)
 
5337
        else:
 
5338
            revision_id = branch.last_revision()
 
5339
        revision_id = ensure_null(revision_id)
 
5340
        if revision_id == NULL_REVISION:
 
5341
            raise errors.BzrCommandError('No revisions to bundle.')
 
5342
        directive = merge_directive.MergeDirective2.from_objects(
 
5343
            branch.repository, revision_id, time.time(),
 
5344
            osutils.local_time_offset(), submit_branch,
 
5345
            public_branch=public_branch, include_patch=include_patch,
 
5346
            include_bundle=include_bundle, message=message,
 
5347
            base_revision_id=base_revision_id)
 
5348
        if mail_to is None:
 
5349
            if sign:
 
5350
                self.outf.write(directive.to_signed(branch))
 
5351
            else:
 
5352
                self.outf.writelines(directive.to_lines())
 
5353
        else:
 
5354
            message = directive.to_email(mail_to, branch, sign)
 
5355
            s = SMTPConnection(branch.get_config())
 
5356
            s.send_email(message)
 
5357
 
 
5358
 
 
5359
class cmd_send(Command):
 
5360
    __doc__ = """Mail or create a merge-directive for submitting changes.
 
5361
 
 
5362
    A merge directive provides many things needed for requesting merges:
 
5363
 
 
5364
    * A machine-readable description of the merge to perform
 
5365
 
 
5366
    * An optional patch that is a preview of the changes requested
 
5367
 
 
5368
    * An optional bundle of revision data, so that the changes can be applied
 
5369
      directly from the merge directive, without retrieving data from a
 
5370
      branch.
 
5371
 
 
5372
    `bzr send` creates a compact data set that, when applied using bzr
 
5373
    merge, has the same effect as merging from the source branch.  
 
5374
    
 
5375
    By default the merge directive is self-contained and can be applied to any
 
5376
    branch containing submit_branch in its ancestory without needing access to
 
5377
    the source branch.
 
5378
    
 
5379
    If --no-bundle is specified, then Bazaar doesn't send the contents of the
 
5380
    revisions, but only a structured request to merge from the
 
5381
    public_location.  In that case the public_branch is needed and it must be
 
5382
    up-to-date and accessible to the recipient.  The public_branch is always
 
5383
    included if known, so that people can check it later.
 
5384
 
 
5385
    The submit branch defaults to the parent of the source branch, but can be
 
5386
    overridden.  Both submit branch and public branch will be remembered in
 
5387
    branch.conf the first time they are used for a particular branch.  The
 
5388
    source branch defaults to that containing the working directory, but can
 
5389
    be changed using --from.
 
5390
 
 
5391
    Both the submit branch and the public branch follow the usual behavior with
 
5392
    respect to --remember: If there is no default location set, the first send
 
5393
    will set it (use --no-remember to avoid settting it). After that, you can
 
5394
    omit the location to use the default.  To change the default, use
 
5395
    --remember. The value will only be saved if the location can be accessed.
 
5396
 
 
5397
    In order to calculate those changes, bzr must analyse the submit branch.
 
5398
    Therefore it is most efficient for the submit branch to be a local mirror.
 
5399
    If a public location is known for the submit_branch, that location is used
 
5400
    in the merge directive.
 
5401
 
 
5402
    The default behaviour is to send the merge directive by mail, unless -o is
 
5403
    given, in which case it is sent to a file.
 
5404
 
 
5405
    Mail is sent using your preferred mail program.  This should be transparent
 
5406
    on Windows (it uses MAPI).  On Unix, it requires the xdg-email utility.
 
5407
    If the preferred client can't be found (or used), your editor will be used.
 
5408
 
 
5409
    To use a specific mail program, set the mail_client configuration option.
 
5410
    (For Thunderbird 1.5, this works around some bugs.)  Supported values for
 
5411
    specific clients are "claws", "evolution", "kmail", "mail.app" (MacOS X's
 
5412
    Mail.app), "mutt", and "thunderbird"; generic options are "default",
 
5413
    "editor", "emacsclient", "mapi", and "xdg-email".  Plugins may also add
 
5414
    supported clients.
 
5415
 
 
5416
    If mail is being sent, a to address is required.  This can be supplied
 
5417
    either on the commandline, by setting the submit_to configuration
 
5418
    option in the branch itself or the child_submit_to configuration option
 
5419
    in the submit branch.
 
5420
 
 
5421
    Two formats are currently supported: "4" uses revision bundle format 4 and
 
5422
    merge directive format 2.  It is significantly faster and smaller than
 
5423
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
 
5424
    default.  "0.9" uses revision bundle format 0.9 and merge directive
 
5425
    format 1.  It is compatible with Bazaar 0.12 - 0.18.
 
5426
 
 
5427
    The merge directives created by bzr send may be applied using bzr merge or
 
5428
    bzr pull by specifying a file containing a merge directive as the location.
 
5429
 
 
5430
    bzr send makes extensive use of public locations to map local locations into
 
5431
    URLs that can be used by other people.  See `bzr help configuration` to
 
5432
    set them, and use `bzr info` to display them.
 
5433
    """
 
5434
 
 
5435
    encoding_type = 'exact'
 
5436
 
 
5437
    _see_also = ['merge', 'pull']
 
5438
 
 
5439
    takes_args = ['submit_branch?', 'public_branch?']
 
5440
 
 
5441
    takes_options = [
 
5442
        Option('no-bundle',
 
5443
               help='Do not include a bundle in the merge directive.'),
 
5444
        Option('no-patch', help='Do not include a preview patch in the merge'
 
5445
               ' directive.'),
 
5446
        Option('remember',
 
5447
               help='Remember submit and public branch.'),
 
5448
        Option('from',
 
5449
               help='Branch to generate the submission from, '
 
5450
               'rather than the one containing the working directory.',
 
5451
               short_name='f',
 
5452
               type=unicode),
 
5453
        Option('output', short_name='o',
 
5454
               help='Write merge directive to this file or directory; '
 
5455
                    'use - for stdout.',
 
5456
               type=unicode),
 
5457
        Option('strict',
 
5458
               help='Refuse to send if there are uncommitted changes in'
 
5459
               ' the working tree, --no-strict disables the check.'),
 
5460
        Option('mail-to', help='Mail the request to this address.',
 
5461
               type=unicode),
 
5462
        'revision',
 
5463
        'message',
 
5464
        Option('body', help='Body for the email.', type=unicode),
 
5465
        RegistryOption('format',
 
5466
                       help='Use the specified output format.',
 
5467
                       lazy_registry=('bzrlib.send', 'format_registry')),
 
5468
        ]
 
5469
 
 
5470
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
 
5471
            no_patch=False, revision=None, remember=None, output=None,
 
5472
            format=None, mail_to=None, message=None, body=None,
 
5473
            strict=None, **kwargs):
 
5474
        from bzrlib.send import send
 
5475
        return send(submit_branch, revision, public_branch, remember,
 
5476
                    format, no_bundle, no_patch, output,
 
5477
                    kwargs.get('from', '.'), mail_to, message, body,
 
5478
                    self.outf,
 
5479
                    strict=strict)
 
5480
 
 
5481
 
 
5482
class cmd_bundle_revisions(cmd_send):
 
5483
    __doc__ = """Create a merge-directive for submitting changes.
 
5484
 
 
5485
    A merge directive provides many things needed for requesting merges:
 
5486
 
 
5487
    * A machine-readable description of the merge to perform
 
5488
 
 
5489
    * An optional patch that is a preview of the changes requested
 
5490
 
 
5491
    * An optional bundle of revision data, so that the changes can be applied
 
5492
      directly from the merge directive, without retrieving data from a
 
5493
      branch.
 
5494
 
 
5495
    If --no-bundle is specified, then public_branch is needed (and must be
 
5496
    up-to-date), so that the receiver can perform the merge using the
 
5497
    public_branch.  The public_branch is always included if known, so that
 
5498
    people can check it later.
 
5499
 
 
5500
    The submit branch defaults to the parent, but can be overridden.  Both
 
5501
    submit branch and public branch will be remembered if supplied.
 
5502
 
 
5503
    If a public_branch is known for the submit_branch, that public submit
 
5504
    branch is used in the merge instructions.  This means that a local mirror
 
5505
    can be used as your actual submit branch, once you have set public_branch
 
5506
    for that mirror.
 
5507
 
 
5508
    Two formats are currently supported: "4" uses revision bundle format 4 and
 
5509
    merge directive format 2.  It is significantly faster and smaller than
 
5510
    older formats.  It is compatible with Bazaar 0.19 and later.  It is the
 
5511
    default.  "0.9" uses revision bundle format 0.9 and merge directive
 
5512
    format 1.  It is compatible with Bazaar 0.12 - 0.18.
 
5513
    """
 
5514
 
 
5515
    takes_options = [
 
5516
        Option('no-bundle',
 
5517
               help='Do not include a bundle in the merge directive.'),
 
5518
        Option('no-patch', help='Do not include a preview patch in the merge'
 
5519
               ' directive.'),
 
5520
        Option('remember',
 
5521
               help='Remember submit and public branch.'),
 
5522
        Option('from',
 
5523
               help='Branch to generate the submission from, '
 
5524
               'rather than the one containing the working directory.',
 
5525
               short_name='f',
 
5526
               type=unicode),
 
5527
        Option('output', short_name='o', help='Write directive to this file.',
 
5528
               type=unicode),
 
5529
        Option('strict',
 
5530
               help='Refuse to bundle revisions if there are uncommitted'
 
5531
               ' changes in the working tree, --no-strict disables the check.'),
 
5532
        'revision',
 
5533
        RegistryOption('format',
 
5534
                       help='Use the specified output format.',
 
5535
                       lazy_registry=('bzrlib.send', 'format_registry')),
 
5536
        ]
 
5537
    aliases = ['bundle']
 
5538
 
 
5539
    _see_also = ['send', 'merge']
 
5540
 
 
5541
    hidden = True
 
5542
 
 
5543
    def run(self, submit_branch=None, public_branch=None, no_bundle=False,
 
5544
            no_patch=False, revision=None, remember=False, output=None,
 
5545
            format=None, strict=None, **kwargs):
 
5546
        if output is None:
 
5547
            output = '-'
 
5548
        from bzrlib.send import send
 
5549
        return send(submit_branch, revision, public_branch, remember,
 
5550
                         format, no_bundle, no_patch, output,
 
5551
                         kwargs.get('from', '.'), None, None, None,
 
5552
                         self.outf, strict=strict)
 
5553
 
 
5554
 
 
5555
class cmd_tag(Command):
 
5556
    __doc__ = """Create, remove or modify a tag naming a revision.
 
5557
 
 
5558
    Tags give human-meaningful names to revisions.  Commands that take a -r
 
5559
    (--revision) option can be given -rtag:X, where X is any previously
 
5560
    created tag.
 
5561
 
 
5562
    Tags are stored in the branch.  Tags are copied from one branch to another
 
5563
    along when you branch, push, pull or merge.
 
5564
 
 
5565
    It is an error to give a tag name that already exists unless you pass
 
5566
    --force, in which case the tag is moved to point to the new revision.
 
5567
 
 
5568
    To rename a tag (change the name but keep it on the same revsion), run ``bzr
 
5569
    tag new-name -r tag:old-name`` and then ``bzr tag --delete oldname``.
 
5570
 
 
5571
    If no tag name is specified it will be determined through the 
 
5572
    'automatic_tag_name' hook. This can e.g. be used to automatically tag
 
5573
    upstream releases by reading configure.ac. See ``bzr help hooks`` for
 
5574
    details.
 
5575
    """
 
5576
 
 
5577
    _see_also = ['commit', 'tags']
 
5578
    takes_args = ['tag_name?']
 
5579
    takes_options = [
 
5580
        Option('delete',
 
5581
            help='Delete this tag rather than placing it.',
 
5582
            ),
 
5583
        custom_help('directory',
 
5584
            help='Branch in which to place the tag.'),
 
5585
        Option('force',
 
5586
            help='Replace existing tags.',
 
5587
            ),
 
5588
        'revision',
 
5589
        ]
 
5590
 
 
5591
    def run(self, tag_name=None,
 
5592
            delete=None,
 
5593
            directory='.',
 
5594
            force=None,
 
5595
            revision=None,
 
5596
            ):
 
5597
        branch, relpath = Branch.open_containing(directory)
 
5598
        self.add_cleanup(branch.lock_write().unlock)
 
5599
        if delete:
 
5600
            if tag_name is None:
 
5601
                raise errors.BzrCommandError("No tag specified to delete.")
 
5602
            branch.tags.delete_tag(tag_name)
 
5603
            note('Deleted tag %s.' % tag_name)
 
5604
        else:
 
5605
            if revision:
 
5606
                if len(revision) != 1:
 
5607
                    raise errors.BzrCommandError(
 
5608
                        "Tags can only be placed on a single revision, "
 
5609
                        "not on a range")
 
5610
                revision_id = revision[0].as_revision_id(branch)
 
5611
            else:
 
5612
                revision_id = branch.last_revision()
 
5613
            if tag_name is None:
 
5614
                tag_name = branch.automatic_tag_name(revision_id)
 
5615
                if tag_name is None:
 
5616
                    raise errors.BzrCommandError(
 
5617
                        "Please specify a tag name.")
 
5618
            if (not force) and branch.tags.has_tag(tag_name):
 
5619
                raise errors.TagAlreadyExists(tag_name)
 
5620
            branch.tags.set_tag(tag_name, revision_id)
 
5621
            note('Created tag %s.' % tag_name)
 
5622
 
 
5623
 
 
5624
class cmd_tags(Command):
 
5625
    __doc__ = """List tags.
 
5626
 
 
5627
    This command shows a table of tag names and the revisions they reference.
 
5628
    """
 
5629
 
 
5630
    _see_also = ['tag']
 
5631
    takes_options = [
 
5632
        custom_help('directory',
 
5633
            help='Branch whose tags should be displayed.'),
 
5634
        RegistryOption('sort',
 
5635
            'Sort tags by different criteria.', title='Sorting',
 
5636
            lazy_registry=('bzrlib.tag', 'tag_sort_methods')
 
5637
            ),
 
5638
        'show-ids',
 
5639
        'revision',
 
5640
    ]
 
5641
 
 
5642
    @display_command
 
5643
    def run(self, directory='.', sort=None, show_ids=False, revision=None):
 
5644
        from bzrlib.tag import tag_sort_methods
 
5645
        branch, relpath = Branch.open_containing(directory)
 
5646
 
 
5647
        tags = branch.tags.get_tag_dict().items()
 
5648
        if not tags:
 
5649
            return
 
5650
 
 
5651
        self.add_cleanup(branch.lock_read().unlock)
 
5652
        if revision:
 
5653
            graph = branch.repository.get_graph()
 
5654
            rev1, rev2 = _get_revision_range(revision, branch, self.name())
 
5655
            revid1, revid2 = rev1.rev_id, rev2.rev_id
 
5656
            # only show revisions between revid1 and revid2 (inclusive)
 
5657
            tags = [(tag, revid) for tag, revid in tags if
 
5658
                graph.is_between(revid, revid1, revid2)]
 
5659
        if sort is None:
 
5660
            sort = tag_sort_methods.get()
 
5661
        sort(branch, tags)
 
5662
        if not show_ids:
 
5663
            # [ (tag, revid), ... ] -> [ (tag, dotted_revno), ... ]
 
5664
            for index, (tag, revid) in enumerate(tags):
 
5665
                try:
 
5666
                    revno = branch.revision_id_to_dotted_revno(revid)
 
5667
                    if isinstance(revno, tuple):
 
5668
                        revno = '.'.join(map(str, revno))
 
5669
                except (errors.NoSuchRevision, errors.GhostRevisionsHaveNoRevno):
 
5670
                    # Bad tag data/merges can lead to tagged revisions
 
5671
                    # which are not in this branch. Fail gracefully ...
 
5672
                    revno = '?'
 
5673
                tags[index] = (tag, revno)
 
5674
        self.cleanup_now()
 
5675
        for tag, revspec in tags:
 
5676
            self.outf.write('%-20s %s\n' % (tag, revspec))
 
5677
 
 
5678
 
 
5679
class cmd_reconfigure(Command):
 
5680
    __doc__ = """Reconfigure the type of a bzr directory.
 
5681
 
 
5682
    A target configuration must be specified.
 
5683
 
 
5684
    For checkouts, the bind-to location will be auto-detected if not specified.
 
5685
    The order of preference is
 
5686
    1. For a lightweight checkout, the current bound location.
 
5687
    2. For branches that used to be checkouts, the previously-bound location.
 
5688
    3. The push location.
 
5689
    4. The parent location.
 
5690
    If none of these is available, --bind-to must be specified.
 
5691
    """
 
5692
 
 
5693
    _see_also = ['branches', 'checkouts', 'standalone-trees', 'working-trees']
 
5694
    takes_args = ['location?']
 
5695
    takes_options = [
 
5696
        RegistryOption.from_kwargs(
 
5697
            'target_type',
 
5698
            title='Target type',
 
5699
            help='The type to reconfigure the directory to.',
 
5700
            value_switches=True, enum_switch=False,
 
5701
            branch='Reconfigure to be an unbound branch with no working tree.',
 
5702
            tree='Reconfigure to be an unbound branch with a working tree.',
 
5703
            checkout='Reconfigure to be a bound branch with a working tree.',
 
5704
            lightweight_checkout='Reconfigure to be a lightweight'
 
5705
                ' checkout (with no local history).',
 
5706
            standalone='Reconfigure to be a standalone branch '
 
5707
                '(i.e. stop using shared repository).',
 
5708
            use_shared='Reconfigure to use a shared repository.',
 
5709
            with_trees='Reconfigure repository to create '
 
5710
                'working trees on branches by default.',
 
5711
            with_no_trees='Reconfigure repository to not create '
 
5712
                'working trees on branches by default.'
 
5713
            ),
 
5714
        Option('bind-to', help='Branch to bind checkout to.', type=str),
 
5715
        Option('force',
 
5716
            help='Perform reconfiguration even if local changes'
 
5717
            ' will be lost.'),
 
5718
        Option('stacked-on',
 
5719
            help='Reconfigure a branch to be stacked on another branch.',
 
5720
            type=unicode,
 
5721
            ),
 
5722
        Option('unstacked',
 
5723
            help='Reconfigure a branch to be unstacked.  This '
 
5724
                'may require copying substantial data into it.',
 
5725
            ),
 
5726
        ]
 
5727
 
 
5728
    def run(self, location=None, target_type=None, bind_to=None, force=False,
 
5729
            stacked_on=None,
 
5730
            unstacked=None):
 
5731
        directory = bzrdir.BzrDir.open(location)
 
5732
        if stacked_on and unstacked:
 
5733
            raise errors.BzrCommandError("Can't use both --stacked-on and --unstacked")
 
5734
        elif stacked_on is not None:
 
5735
            reconfigure.ReconfigureStackedOn().apply(directory, stacked_on)
 
5736
        elif unstacked:
 
5737
            reconfigure.ReconfigureUnstacked().apply(directory)
 
5738
        # At the moment you can use --stacked-on and a different
 
5739
        # reconfiguration shape at the same time; there seems no good reason
 
5740
        # to ban it.
 
5741
        if target_type is None:
 
5742
            if stacked_on or unstacked:
 
5743
                return
 
5744
            else:
 
5745
                raise errors.BzrCommandError('No target configuration '
 
5746
                    'specified')
 
5747
        elif target_type == 'branch':
 
5748
            reconfiguration = reconfigure.Reconfigure.to_branch(directory)
 
5749
        elif target_type == 'tree':
 
5750
            reconfiguration = reconfigure.Reconfigure.to_tree(directory)
 
5751
        elif target_type == 'checkout':
 
5752
            reconfiguration = reconfigure.Reconfigure.to_checkout(
 
5753
                directory, bind_to)
 
5754
        elif target_type == 'lightweight-checkout':
 
5755
            reconfiguration = reconfigure.Reconfigure.to_lightweight_checkout(
 
5756
                directory, bind_to)
 
5757
        elif target_type == 'use-shared':
 
5758
            reconfiguration = reconfigure.Reconfigure.to_use_shared(directory)
 
5759
        elif target_type == 'standalone':
 
5760
            reconfiguration = reconfigure.Reconfigure.to_standalone(directory)
 
5761
        elif target_type == 'with-trees':
 
5762
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
 
5763
                directory, True)
 
5764
        elif target_type == 'with-no-trees':
 
5765
            reconfiguration = reconfigure.Reconfigure.set_repository_trees(
 
5766
                directory, False)
 
5767
        reconfiguration.apply(force)
 
5768
 
 
5769
 
 
5770
class cmd_switch(Command):
 
5771
    __doc__ = """Set the branch of a checkout and update.
 
5772
 
 
5773
    For lightweight checkouts, this changes the branch being referenced.
 
5774
    For heavyweight checkouts, this checks that there are no local commits
 
5775
    versus the current bound branch, then it makes the local branch a mirror
 
5776
    of the new location and binds to it.
 
5777
 
 
5778
    In both cases, the working tree is updated and uncommitted changes
 
5779
    are merged. The user can commit or revert these as they desire.
 
5780
 
 
5781
    Pending merges need to be committed or reverted before using switch.
 
5782
 
 
5783
    The path to the branch to switch to can be specified relative to the parent
 
5784
    directory of the current branch. For example, if you are currently in a
 
5785
    checkout of /path/to/branch, specifying 'newbranch' will find a branch at
 
5786
    /path/to/newbranch.
 
5787
 
 
5788
    Bound branches use the nickname of its master branch unless it is set
 
5789
    locally, in which case switching will update the local nickname to be
 
5790
    that of the master.
 
5791
    """
 
5792
 
 
5793
    takes_args = ['to_location?']
 
5794
    takes_options = ['directory',
 
5795
                     Option('force',
 
5796
                        help='Switch even if local commits will be lost.'),
 
5797
                     'revision',
 
5798
                     Option('create-branch', short_name='b',
 
5799
                        help='Create the target branch from this one before'
 
5800
                             ' switching to it.'),
 
5801
                    ]
 
5802
 
 
5803
    def run(self, to_location=None, force=False, create_branch=False,
 
5804
            revision=None, directory=u'.'):
 
5805
        from bzrlib import switch
 
5806
        tree_location = directory
 
5807
        revision = _get_one_revision('switch', revision)
 
5808
        control_dir = bzrdir.BzrDir.open_containing(tree_location)[0]
 
5809
        if to_location is None:
 
5810
            if revision is None:
 
5811
                raise errors.BzrCommandError('You must supply either a'
 
5812
                                             ' revision or a location')
 
5813
            to_location = tree_location
 
5814
        try:
 
5815
            branch = control_dir.open_branch()
 
5816
            had_explicit_nick = branch.get_config().has_explicit_nickname()
 
5817
        except errors.NotBranchError:
 
5818
            branch = None
 
5819
            had_explicit_nick = False
 
5820
        if create_branch:
 
5821
            if branch is None:
 
5822
                raise errors.BzrCommandError('cannot create branch without'
 
5823
                                             ' source branch')
 
5824
            to_location = directory_service.directories.dereference(
 
5825
                              to_location)
 
5826
            if '/' not in to_location and '\\' not in to_location:
 
5827
                # This path is meant to be relative to the existing branch
 
5828
                this_url = self._get_branch_location(control_dir)
 
5829
                to_location = urlutils.join(this_url, '..', to_location)
 
5830
            to_branch = branch.bzrdir.sprout(to_location,
 
5831
                                 possible_transports=[branch.bzrdir.root_transport],
 
5832
                                 source_branch=branch).open_branch()
 
5833
        else:
 
5834
            try:
 
5835
                to_branch = Branch.open(to_location)
 
5836
            except errors.NotBranchError:
 
5837
                this_url = self._get_branch_location(control_dir)
 
5838
                to_branch = Branch.open(
 
5839
                    urlutils.join(this_url, '..', to_location))
 
5840
        if revision is not None:
 
5841
            revision = revision.as_revision_id(to_branch)
 
5842
        switch.switch(control_dir, to_branch, force, revision_id=revision)
 
5843
        if had_explicit_nick:
 
5844
            branch = control_dir.open_branch() #get the new branch!
 
5845
            branch.nick = to_branch.nick
 
5846
        note('Switched to branch: %s',
 
5847
            urlutils.unescape_for_display(to_branch.base, 'utf-8'))
 
5848
 
 
5849
    def _get_branch_location(self, control_dir):
 
5850
        """Return location of branch for this control dir."""
 
5851
        try:
 
5852
            this_branch = control_dir.open_branch()
 
5853
            # This may be a heavy checkout, where we want the master branch
 
5854
            master_location = this_branch.get_bound_location()
 
5855
            if master_location is not None:
 
5856
                return master_location
 
5857
            # If not, use a local sibling
 
5858
            return this_branch.base
 
5859
        except errors.NotBranchError:
 
5860
            format = control_dir.find_branch_format()
 
5861
            if getattr(format, 'get_reference', None) is not None:
 
5862
                return format.get_reference(control_dir)
 
5863
            else:
 
5864
                return control_dir.root_transport.base
 
5865
 
 
5866
 
 
5867
class cmd_view(Command):
 
5868
    __doc__ = """Manage filtered views.
 
5869
 
 
5870
    Views provide a mask over the tree so that users can focus on
 
5871
    a subset of a tree when doing their work. After creating a view,
 
5872
    commands that support a list of files - status, diff, commit, etc -
 
5873
    effectively have that list of files implicitly given each time.
 
5874
    An explicit list of files can still be given but those files
 
5875
    must be within the current view.
 
5876
 
 
5877
    In most cases, a view has a short life-span: it is created to make
 
5878
    a selected change and is deleted once that change is committed.
 
5879
    At other times, you may wish to create one or more named views
 
5880
    and switch between them.
 
5881
 
 
5882
    To disable the current view without deleting it, you can switch to
 
5883
    the pseudo view called ``off``. This can be useful when you need
 
5884
    to see the whole tree for an operation or two (e.g. merge) but
 
5885
    want to switch back to your view after that.
 
5886
 
 
5887
    :Examples:
 
5888
      To define the current view::
 
5889
 
 
5890
        bzr view file1 dir1 ...
 
5891
 
 
5892
      To list the current view::
 
5893
 
 
5894
        bzr view
 
5895
 
 
5896
      To delete the current view::
 
5897
 
 
5898
        bzr view --delete
 
5899
 
 
5900
      To disable the current view without deleting it::
 
5901
 
 
5902
        bzr view --switch off
 
5903
 
 
5904
      To define a named view and switch to it::
 
5905
 
 
5906
        bzr view --name view-name file1 dir1 ...
 
5907
 
 
5908
      To list a named view::
 
5909
 
 
5910
        bzr view --name view-name
 
5911
 
 
5912
      To delete a named view::
 
5913
 
 
5914
        bzr view --name view-name --delete
 
5915
 
 
5916
      To switch to a named view::
 
5917
 
 
5918
        bzr view --switch view-name
 
5919
 
 
5920
      To list all views defined::
 
5921
 
 
5922
        bzr view --all
 
5923
 
 
5924
      To delete all views::
 
5925
 
 
5926
        bzr view --delete --all
 
5927
    """
 
5928
 
 
5929
    _see_also = []
 
5930
    takes_args = ['file*']
 
5931
    takes_options = [
 
5932
        Option('all',
 
5933
            help='Apply list or delete action to all views.',
 
5934
            ),
 
5935
        Option('delete',
 
5936
            help='Delete the view.',
 
5937
            ),
 
5938
        Option('name',
 
5939
            help='Name of the view to define, list or delete.',
 
5940
            type=unicode,
 
5941
            ),
 
5942
        Option('switch',
 
5943
            help='Name of the view to switch to.',
 
5944
            type=unicode,
 
5945
            ),
 
5946
        ]
 
5947
 
 
5948
    def run(self, file_list,
 
5949
            all=False,
 
5950
            delete=False,
 
5951
            name=None,
 
5952
            switch=None,
 
5953
            ):
 
5954
        tree, file_list = WorkingTree.open_containing_paths(file_list,
 
5955
            apply_view=False)
 
5956
        current_view, view_dict = tree.views.get_view_info()
 
5957
        if name is None:
 
5958
            name = current_view
 
5959
        if delete:
 
5960
            if file_list:
 
5961
                raise errors.BzrCommandError(
 
5962
                    "Both --delete and a file list specified")
 
5963
            elif switch:
 
5964
                raise errors.BzrCommandError(
 
5965
                    "Both --delete and --switch specified")
 
5966
            elif all:
 
5967
                tree.views.set_view_info(None, {})
 
5968
                self.outf.write("Deleted all views.\n")
 
5969
            elif name is None:
 
5970
                raise errors.BzrCommandError("No current view to delete")
 
5971
            else:
 
5972
                tree.views.delete_view(name)
 
5973
                self.outf.write("Deleted '%s' view.\n" % name)
 
5974
        elif switch:
 
5975
            if file_list:
 
5976
                raise errors.BzrCommandError(
 
5977
                    "Both --switch and a file list specified")
 
5978
            elif all:
 
5979
                raise errors.BzrCommandError(
 
5980
                    "Both --switch and --all specified")
 
5981
            elif switch == 'off':
 
5982
                if current_view is None:
 
5983
                    raise errors.BzrCommandError("No current view to disable")
 
5984
                tree.views.set_view_info(None, view_dict)
 
5985
                self.outf.write("Disabled '%s' view.\n" % (current_view))
 
5986
            else:
 
5987
                tree.views.set_view_info(switch, view_dict)
 
5988
                view_str = views.view_display_str(tree.views.lookup_view())
 
5989
                self.outf.write("Using '%s' view: %s\n" % (switch, view_str))
 
5990
        elif all:
 
5991
            if view_dict:
 
5992
                self.outf.write('Views defined:\n')
 
5993
                for view in sorted(view_dict):
 
5994
                    if view == current_view:
 
5995
                        active = "=>"
 
5996
                    else:
 
5997
                        active = "  "
 
5998
                    view_str = views.view_display_str(view_dict[view])
 
5999
                    self.outf.write('%s %-20s %s\n' % (active, view, view_str))
 
6000
            else:
 
6001
                self.outf.write('No views defined.\n')
 
6002
        elif file_list:
 
6003
            if name is None:
 
6004
                # No name given and no current view set
 
6005
                name = 'my'
 
6006
            elif name == 'off':
 
6007
                raise errors.BzrCommandError(
 
6008
                    "Cannot change the 'off' pseudo view")
 
6009
            tree.views.set_view(name, sorted(file_list))
 
6010
            view_str = views.view_display_str(tree.views.lookup_view())
 
6011
            self.outf.write("Using '%s' view: %s\n" % (name, view_str))
 
6012
        else:
 
6013
            # list the files
 
6014
            if name is None:
 
6015
                # No name given and no current view set
 
6016
                self.outf.write('No current view.\n')
 
6017
            else:
 
6018
                view_str = views.view_display_str(tree.views.lookup_view(name))
 
6019
                self.outf.write("'%s' view is: %s\n" % (name, view_str))
 
6020
 
 
6021
 
 
6022
class cmd_hooks(Command):
 
6023
    __doc__ = """Show hooks."""
 
6024
 
 
6025
    hidden = True
 
6026
 
 
6027
    def run(self):
 
6028
        for hook_key in sorted(hooks.known_hooks.keys()):
 
6029
            some_hooks = hooks.known_hooks_key_to_object(hook_key)
 
6030
            self.outf.write("%s:\n" % type(some_hooks).__name__)
 
6031
            for hook_name, hook_point in sorted(some_hooks.items()):
 
6032
                self.outf.write("  %s:\n" % (hook_name,))
 
6033
                found_hooks = list(hook_point)
 
6034
                if found_hooks:
 
6035
                    for hook in found_hooks:
 
6036
                        self.outf.write("    %s\n" %
 
6037
                                        (some_hooks.get_hook_name(hook),))
 
6038
                else:
 
6039
                    self.outf.write("    <no hooks installed>\n")
 
6040
 
 
6041
 
 
6042
class cmd_remove_branch(Command):
 
6043
    __doc__ = """Remove a branch.
 
6044
 
 
6045
    This will remove the branch from the specified location but 
 
6046
    will keep any working tree or repository in place.
 
6047
 
 
6048
    :Examples:
 
6049
 
 
6050
      Remove the branch at repo/trunk::
 
6051
 
 
6052
        bzr remove-branch repo/trunk
 
6053
 
 
6054
    """
 
6055
 
 
6056
    takes_args = ["location?"]
 
6057
 
 
6058
    aliases = ["rmbranch"]
 
6059
 
 
6060
    def run(self, location=None):
 
6061
        if location is None:
 
6062
            location = "."
 
6063
        branch = Branch.open_containing(location)[0]
 
6064
        branch.bzrdir.destroy_branch()
 
6065
 
 
6066
 
 
6067
class cmd_shelve(Command):
 
6068
    __doc__ = """Temporarily set aside some changes from the current tree.
 
6069
 
 
6070
    Shelve allows you to temporarily put changes you've made "on the shelf",
 
6071
    ie. out of the way, until a later time when you can bring them back from
 
6072
    the shelf with the 'unshelve' command.  The changes are stored alongside
 
6073
    your working tree, and so they aren't propagated along with your branch nor
 
6074
    will they survive its deletion.
 
6075
 
 
6076
    If shelve --list is specified, previously-shelved changes are listed.
 
6077
 
 
6078
    Shelve is intended to help separate several sets of changes that have
 
6079
    been inappropriately mingled.  If you just want to get rid of all changes
 
6080
    and you don't need to restore them later, use revert.  If you want to
 
6081
    shelve all text changes at once, use shelve --all.
 
6082
 
 
6083
    If filenames are specified, only the changes to those files will be
 
6084
    shelved. Other files will be left untouched.
 
6085
 
 
6086
    If a revision is specified, changes since that revision will be shelved.
 
6087
 
 
6088
    You can put multiple items on the shelf, and by default, 'unshelve' will
 
6089
    restore the most recently shelved changes.
 
6090
 
 
6091
    For complicated changes, it is possible to edit the changes in a separate
 
6092
    editor program to decide what the file remaining in the working copy
 
6093
    should look like.  To do this, add the configuration option
 
6094
 
 
6095
        change_editor = PROGRAM @new_path @old_path
 
6096
 
 
6097
    where @new_path is replaced with the path of the new version of the 
 
6098
    file and @old_path is replaced with the path of the old version of 
 
6099
    the file.  The PROGRAM should save the new file with the desired 
 
6100
    contents of the file in the working tree.
 
6101
        
 
6102
    """
 
6103
 
 
6104
    takes_args = ['file*']
 
6105
 
 
6106
    takes_options = [
 
6107
        'directory',
 
6108
        'revision',
 
6109
        Option('all', help='Shelve all changes.'),
 
6110
        'message',
 
6111
        RegistryOption('writer', 'Method to use for writing diffs.',
 
6112
                       bzrlib.option.diff_writer_registry,
 
6113
                       value_switches=True, enum_switch=False),
 
6114
 
 
6115
        Option('list', help='List shelved changes.'),
 
6116
        Option('destroy',
 
6117
               help='Destroy removed changes instead of shelving them.'),
 
6118
    ]
 
6119
    _see_also = ['unshelve', 'configuration']
 
6120
 
 
6121
    def run(self, revision=None, all=False, file_list=None, message=None,
 
6122
            writer=None, list=False, destroy=False, directory=None):
 
6123
        if list:
 
6124
            return self.run_for_list(directory=directory)
 
6125
        from bzrlib.shelf_ui import Shelver
 
6126
        if writer is None:
 
6127
            writer = bzrlib.option.diff_writer_registry.get()
 
6128
        try:
 
6129
            shelver = Shelver.from_args(writer(sys.stdout), revision, all,
 
6130
                file_list, message, destroy=destroy, directory=directory)
 
6131
            try:
 
6132
                shelver.run()
 
6133
            finally:
 
6134
                shelver.finalize()
 
6135
        except errors.UserAbort:
 
6136
            return 0
 
6137
 
 
6138
    def run_for_list(self, directory=None):
 
6139
        if directory is None:
 
6140
            directory = u'.'
 
6141
        tree = WorkingTree.open_containing(directory)[0]
 
6142
        self.add_cleanup(tree.lock_read().unlock)
 
6143
        manager = tree.get_shelf_manager()
 
6144
        shelves = manager.active_shelves()
 
6145
        if len(shelves) == 0:
 
6146
            note('No shelved changes.')
 
6147
            return 0
 
6148
        for shelf_id in reversed(shelves):
 
6149
            message = manager.get_metadata(shelf_id).get('message')
 
6150
            if message is None:
 
6151
                message = '<no message>'
 
6152
            self.outf.write('%3d: %s\n' % (shelf_id, message))
 
6153
        return 1
 
6154
 
 
6155
 
 
6156
class cmd_unshelve(Command):
 
6157
    __doc__ = """Restore shelved changes.
 
6158
 
 
6159
    By default, the most recently shelved changes are restored. However if you
 
6160
    specify a shelf by id those changes will be restored instead.  This works
 
6161
    best when the changes don't depend on each other.
 
6162
    """
 
6163
 
 
6164
    takes_args = ['shelf_id?']
 
6165
    takes_options = [
 
6166
        'directory',
 
6167
        RegistryOption.from_kwargs(
 
6168
            'action', help="The action to perform.",
 
6169
            enum_switch=False, value_switches=True,
 
6170
            apply="Apply changes and remove from the shelf.",
 
6171
            dry_run="Show changes, but do not apply or remove them.",
 
6172
            preview="Instead of unshelving the changes, show the diff that "
 
6173
                    "would result from unshelving.",
 
6174
            delete_only="Delete changes without applying them.",
 
6175
            keep="Apply changes but don't delete them.",
 
6176
        )
 
6177
    ]
 
6178
    _see_also = ['shelve']
 
6179
 
 
6180
    def run(self, shelf_id=None, action='apply', directory=u'.'):
 
6181
        from bzrlib.shelf_ui import Unshelver
 
6182
        unshelver = Unshelver.from_args(shelf_id, action, directory=directory)
 
6183
        try:
 
6184
            unshelver.run()
 
6185
        finally:
 
6186
            unshelver.tree.unlock()
 
6187
 
 
6188
 
 
6189
class cmd_clean_tree(Command):
 
6190
    __doc__ = """Remove unwanted files from working tree.
 
6191
 
 
6192
    By default, only unknown files, not ignored files, are deleted.  Versioned
 
6193
    files are never deleted.
 
6194
 
 
6195
    Another class is 'detritus', which includes files emitted by bzr during
 
6196
    normal operations and selftests.  (The value of these files decreases with
 
6197
    time.)
 
6198
 
 
6199
    If no options are specified, unknown files are deleted.  Otherwise, option
 
6200
    flags are respected, and may be combined.
 
6201
 
 
6202
    To check what clean-tree will do, use --dry-run.
 
6203
    """
 
6204
    takes_options = ['directory',
 
6205
                     Option('ignored', help='Delete all ignored files.'),
 
6206
                     Option('detritus', help='Delete conflict files, merge and revert'
 
6207
                            ' backups, and failed selftest dirs.'),
 
6208
                     Option('unknown',
 
6209
                            help='Delete files unknown to bzr (default).'),
 
6210
                     Option('dry-run', help='Show files to delete instead of'
 
6211
                            ' deleting them.'),
 
6212
                     Option('force', help='Do not prompt before deleting.')]
 
6213
    def run(self, unknown=False, ignored=False, detritus=False, dry_run=False,
 
6214
            force=False, directory=u'.'):
 
6215
        from bzrlib.clean_tree import clean_tree
 
6216
        if not (unknown or ignored or detritus):
 
6217
            unknown = True
 
6218
        if dry_run:
 
6219
            force = True
 
6220
        clean_tree(directory, unknown=unknown, ignored=ignored,
 
6221
                   detritus=detritus, dry_run=dry_run, no_prompt=force)
 
6222
 
 
6223
 
 
6224
class cmd_reference(Command):
 
6225
    __doc__ = """list, view and set branch locations for nested trees.
 
6226
 
 
6227
    If no arguments are provided, lists the branch locations for nested trees.
 
6228
    If one argument is provided, display the branch location for that tree.
 
6229
    If two arguments are provided, set the branch location for that tree.
 
6230
    """
 
6231
 
 
6232
    hidden = True
 
6233
 
 
6234
    takes_args = ['path?', 'location?']
 
6235
 
 
6236
    def run(self, path=None, location=None):
 
6237
        branchdir = '.'
 
6238
        if path is not None:
 
6239
            branchdir = path
 
6240
        tree, branch, relpath =(
 
6241
            bzrdir.BzrDir.open_containing_tree_or_branch(branchdir))
 
6242
        if path is not None:
 
6243
            path = relpath
 
6244
        if tree is None:
 
6245
            tree = branch.basis_tree()
 
6246
        if path is None:
 
6247
            info = branch._get_all_reference_info().iteritems()
 
6248
            self._display_reference_info(tree, branch, info)
 
6249
        else:
 
6250
            file_id = tree.path2id(path)
 
6251
            if file_id is None:
 
6252
                raise errors.NotVersionedError(path)
 
6253
            if location is None:
 
6254
                info = [(file_id, branch.get_reference_info(file_id))]
 
6255
                self._display_reference_info(tree, branch, info)
 
6256
            else:
 
6257
                branch.set_reference_info(file_id, path, location)
 
6258
 
 
6259
    def _display_reference_info(self, tree, branch, info):
 
6260
        ref_list = []
 
6261
        for file_id, (path, location) in info:
 
6262
            try:
 
6263
                path = tree.id2path(file_id)
 
6264
            except errors.NoSuchId:
 
6265
                pass
 
6266
            ref_list.append((path, location))
 
6267
        for path, location in sorted(ref_list):
 
6268
            self.outf.write('%s %s\n' % (path, location))
 
6269
 
 
6270
 
 
6271
class cmd_export_pot(Command):
 
6272
    __doc__ = """Export command helps and error messages in po format."""
 
6273
 
 
6274
    hidden = True
 
6275
 
 
6276
    def run(self):
 
6277
        from bzrlib.export_pot import export_pot
 
6278
        export_pot(self.outf)
 
6279
 
 
6280
 
 
6281
def _register_lazy_builtins():
 
6282
    # register lazy builtins from other modules; called at startup and should
 
6283
    # be only called once.
 
6284
    for (name, aliases, module_name) in [
 
6285
        ('cmd_bundle_info', [], 'bzrlib.bundle.commands'),
 
6286
        ('cmd_config', [], 'bzrlib.config'),
 
6287
        ('cmd_dpush', [], 'bzrlib.foreign'),
 
6288
        ('cmd_version_info', [], 'bzrlib.cmd_version_info'),
 
6289
        ('cmd_resolve', ['resolved'], 'bzrlib.conflicts'),
 
6290
        ('cmd_conflicts', [], 'bzrlib.conflicts'),
 
6291
        ('cmd_sign_my_commits', [], 'bzrlib.commit_signature_commands'),
 
6292
        ('cmd_verify_signatures', [],
 
6293
                                        'bzrlib.commit_signature_commands'),
 
6294
        ('cmd_test_script', [], 'bzrlib.cmd_test_script'),
 
6295
        ]:
 
6296
        builtin_command_registry.register_lazy(name, aliases, module_name)