~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Wouter van Heyst
  • Date: 2006-06-07 16:05:27 UTC
  • mto: This revision was merged to the branch mainline in revision 1752.
  • Revision ID: larstiq@larstiq.dyndns.org-20060607160527-2b3649154d0e2e84
more code cleanup

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
# Copyright (C) 2004, 2005, 2006, 2007 Canonical Ltd
2
 
#
 
1
# Copyright (C) 2004, 2005, 2006 by Canonical Ltd
 
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
5
5
# the Free Software Foundation; either version 2 of the License, or
6
6
# (at your option) any later version.
7
 
#
 
7
 
8
8
# This program is distributed in the hope that it will be useful,
9
9
# but WITHOUT ANY WARRANTY; without even the implied warranty of
10
10
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11
11
# GNU General Public License for more details.
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
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
"""builtin bzr commands"""
18
18
 
19
 
import os
20
 
from StringIO import StringIO
21
19
 
22
 
from bzrlib.lazy_import import lazy_import
23
 
lazy_import(globals(), """
24
20
import codecs
25
21
import errno
 
22
import os
 
23
from shutil import rmtree
26
24
import sys
27
 
import tempfile
28
 
import time
29
25
 
30
26
import bzrlib
31
 
from bzrlib import (
32
 
    branch,
33
 
    bugtracker,
34
 
    bundle,
35
 
    bzrdir,
36
 
    delta,
37
 
    config,
38
 
    errors,
39
 
    globbing,
40
 
    ignores,
41
 
    log,
42
 
    merge as _mod_merge,
43
 
    merge_directive,
44
 
    osutils,
45
 
    registry,
46
 
    repository,
47
 
    revisionspec,
48
 
    symbol_versioning,
49
 
    transport,
50
 
    tree as _mod_tree,
51
 
    ui,
52
 
    urlutils,
53
 
    )
 
27
import bzrlib.branch
54
28
from bzrlib.branch import Branch
55
 
from bzrlib.bundle.apply_bundle import install_bundle, merge_bundle
56
 
from bzrlib.conflicts import ConflictList
 
29
import bzrlib.bzrdir as bzrdir
 
30
from bzrlib.bundle.read_bundle import BundleReader
 
31
from bzrlib.bundle.apply_bundle import merge_bundle
 
32
from bzrlib.commands import Command, display_command
 
33
import bzrlib.errors as errors
 
34
from bzrlib.errors import (BzrError, BzrCheckError, BzrCommandError, 
 
35
                           NotBranchError, DivergedBranches, NotConflicted,
 
36
                           NoSuchFile, NoWorkingTree, FileInWrongBranch,
 
37
                           NotVersionedError, BadBundle)
 
38
from bzrlib.log import show_one_log
 
39
from bzrlib.merge import Merge3Merger
 
40
from bzrlib.option import Option
 
41
import bzrlib.osutils
 
42
from bzrlib.progress import DummyProgress, ProgressPhase
 
43
from bzrlib.revision import common_ancestor
57
44
from bzrlib.revisionspec import RevisionSpec
58
 
from bzrlib.smtp_connection import SMTPConnection
 
45
import bzrlib.trace
 
46
from bzrlib.trace import mutter, note, log_error, warning, is_quiet
 
47
from bzrlib.transport.local import LocalTransport
 
48
import bzrlib.ui
 
49
import bzrlib.urlutils as urlutils
59
50
from bzrlib.workingtree import WorkingTree
60
 
""")
61
 
 
62
 
from bzrlib.commands import Command, display_command
63
 
from bzrlib.option import ListOption, Option, RegistryOption
64
 
from bzrlib.progress import DummyProgress, ProgressPhase
65
 
from bzrlib.trace import mutter, note, log_error, warning, is_quiet, info
66
51
 
67
52
 
68
53
def tree_files(file_list, default_branch=u'.'):
69
54
    try:
70
55
        return internal_tree_files(file_list, default_branch)
71
 
    except errors.FileInWrongBranch, e:
72
 
        raise errors.BzrCommandError("%s is not in the same branch as %s" %
73
 
                                     (e.path, file_list[0]))
 
56
    except FileInWrongBranch, e:
 
57
        raise BzrCommandError("%s is not in the same branch as %s" %
 
58
                             (e.path, file_list[0]))
74
59
 
75
60
 
76
61
# XXX: Bad function name; should possibly also be a class method of
85
70
 
86
71
    :param file_list: Filenames to convert.  
87
72
 
88
 
    :param default_branch: Fallback tree path to use if file_list is empty or
89
 
        None.
 
73
    :param default_branch: Fallback tree path to use if file_list is empty or None.
90
74
 
91
75
    :return: workingtree, [relative_paths]
92
76
    """
93
77
    if file_list is None or len(file_list) == 0:
94
78
        return WorkingTree.open_containing(default_branch)[0], file_list
95
 
    tree = WorkingTree.open_containing(osutils.realpath(file_list[0]))[0]
 
79
    tree = WorkingTree.open_containing(file_list[0])[0]
96
80
    new_list = []
97
81
    for filename in file_list:
98
82
        try:
99
 
            new_list.append(tree.relpath(osutils.dereference_path(filename)))
 
83
            new_list.append(tree.relpath(filename))
100
84
        except errors.PathNotChild:
101
 
            raise errors.FileInWrongBranch(tree.branch, filename)
 
85
            raise FileInWrongBranch(tree.branch, filename)
102
86
    return tree, new_list
103
87
 
104
88
 
105
 
@symbol_versioning.deprecated_function(symbol_versioning.zero_fifteen)
106
89
def get_format_type(typestring):
107
90
    """Parse and return a format specifier."""
108
 
    # Have to use BzrDirMetaFormat1 directly, so that
109
 
    # RepositoryFormat.set_default_format works
 
91
    if typestring == "weave":
 
92
        return bzrdir.BzrDirFormat6()
110
93
    if typestring == "default":
111
94
        return bzrdir.BzrDirMetaFormat1()
112
 
    try:
113
 
        return bzrdir.format_registry.make_bzrdir(typestring)
114
 
    except KeyError:
115
 
        msg = 'Unknown bzr format "%s". See "bzr help formats".' % typestring
116
 
        raise errors.BzrCommandError(msg)
 
95
    if typestring == "metaweave":
 
96
        format = bzrdir.BzrDirMetaFormat1()
 
97
        format.repository_format = bzrlib.repository.RepositoryFormat7()
 
98
        return format
 
99
    if typestring == "knit":
 
100
        format = bzrdir.BzrDirMetaFormat1()
 
101
        format.repository_format = bzrlib.repository.RepositoryFormatKnit1()
 
102
        return format
 
103
    msg = "Unknown bzr format %s. Current formats are: default, knit,\n" \
 
104
          "metaweave and weave" % typestring
 
105
    raise BzrCommandError(msg)
117
106
 
118
107
 
119
108
# TODO: Make sure no commands unconditionally use the working directory as a
143
132
    modified
144
133
        Text has changed since the previous revision.
145
134
 
146
 
    kind changed
147
 
        File kind has been changed (e.g. from file to directory).
 
135
    unchanged
 
136
        Nothing about this file has changed since the previous revision.
 
137
        Only shown with --all.
148
138
 
149
139
    unknown
150
140
        Not versioned and not matching an ignore pattern.
151
141
 
152
 
    To see ignored files use 'bzr ignored'.  For details on the
 
142
    To see ignored files use 'bzr ignored'.  For details in the
153
143
    changes to file texts, use 'bzr diff'.
154
 
    
155
 
    --short gives a status flags for each item, similar to the SVN's status
156
 
    command.
157
144
 
158
145
    If no arguments are specified, the status of the entire working
159
146
    directory is shown.  Otherwise, only the status of the specified
167
154
    # TODO: --no-recurse, --recurse options
168
155
    
169
156
    takes_args = ['file*']
170
 
    takes_options = ['show-ids', 'revision',
171
 
                     Option('short', help='Give short SVN-style status lines'),
172
 
                     Option('versioned', help='Only show versioned files')]
 
157
    takes_options = ['all', 'show-ids', 'revision']
173
158
    aliases = ['st', 'stat']
174
159
 
175
160
    encoding_type = 'replace'
176
 
    _see_also = ['diff', 'revert', 'status-flags']
177
161
    
178
162
    @display_command
179
 
    def run(self, show_ids=False, file_list=None, revision=None, short=False,
180
 
            versioned=False):
 
163
    def run(self, all=False, show_ids=False, file_list=None, revision=None):
181
164
        from bzrlib.status import show_tree_status
182
165
 
183
166
        tree, file_list = tree_files(file_list)
184
167
            
185
 
        show_tree_status(tree, show_ids=show_ids,
 
168
        show_tree_status(tree, show_unchanged=all, show_ids=show_ids,
186
169
                         specific_files=file_list, revision=revision,
187
 
                         to_file=self.outf, short=short, versioned=versioned)
 
170
                         to_file=self.outf)
188
171
 
189
172
 
190
173
class cmd_cat_revision(Command):
203
186
    @display_command
204
187
    def run(self, revision_id=None, revision=None):
205
188
 
206
 
        revision_id = osutils.safe_revision_id(revision_id, warn=False)
207
189
        if revision_id is not None and revision is not None:
208
 
            raise errors.BzrCommandError('You can only supply one of'
209
 
                                         ' revision_id or --revision')
 
190
            raise BzrCommandError('You can only supply one of revision_id or --revision')
210
191
        if revision_id is None and revision is None:
211
 
            raise errors.BzrCommandError('You must supply either'
212
 
                                         ' --revision or a revision_id')
 
192
            raise BzrCommandError('You must supply either --revision or a revision_id')
213
193
        b = WorkingTree.open_containing(u'.')[0].branch
214
194
 
215
195
        # TODO: jam 20060112 should cat-revision always output utf-8?
218
198
        elif revision is not None:
219
199
            for rev in revision:
220
200
                if rev is None:
221
 
                    raise errors.BzrCommandError('You cannot specify a NULL'
222
 
                                                 ' revision.')
 
201
                    raise BzrCommandError('You cannot specify a NULL revision.')
223
202
                revno, rev_id = rev.in_history(b)
224
203
                self.outf.write(b.repository.get_revision_xml(rev_id).decode('utf-8'))
225
204
    
226
205
 
227
 
class cmd_remove_tree(Command):
228
 
    """Remove the working tree from a given branch/checkout.
229
 
 
230
 
    Since a lightweight checkout is little more than a working tree
231
 
    this will refuse to run against one.
232
 
 
233
 
    To re-create the working tree, use "bzr checkout".
234
 
    """
235
 
    _see_also = ['checkout', 'working-trees']
236
 
 
237
 
    takes_args = ['location?']
238
 
 
239
 
    def run(self, location='.'):
240
 
        d = bzrdir.BzrDir.open(location)
241
 
        
242
 
        try:
243
 
            working = d.open_workingtree()
244
 
        except errors.NoWorkingTree:
245
 
            raise errors.BzrCommandError("No working tree to remove")
246
 
        except errors.NotLocalUrl:
247
 
            raise errors.BzrCommandError("You cannot remove the working tree of a "
248
 
                                         "remote path")
249
 
        
250
 
        working_path = working.bzrdir.root_transport.base
251
 
        branch_path = working.branch.bzrdir.root_transport.base
252
 
        if working_path != branch_path:
253
 
            raise errors.BzrCommandError("You cannot remove the working tree from "
254
 
                                         "a lightweight checkout")
255
 
        
256
 
        d.destroy_workingtree()
257
 
        
258
 
 
259
206
class cmd_revno(Command):
260
207
    """Show current revision number.
261
208
 
262
209
    This is equal to the number of revisions on this branch.
263
210
    """
264
211
 
265
 
    _see_also = ['info']
266
212
    takes_args = ['location?']
267
213
 
268
214
    @display_command
286
232
            revs.extend(revision)
287
233
        if revision_info_list is not None:
288
234
            for rev in revision_info_list:
289
 
                revs.append(RevisionSpec.from_string(rev))
290
 
 
291
 
        b = Branch.open_containing(u'.')[0]
292
 
 
 
235
                revs.append(RevisionSpec(rev))
293
236
        if len(revs) == 0:
294
 
            revs.append(RevisionSpec.from_string('-1'))
 
237
            raise BzrCommandError('You must supply a revision identifier')
 
238
 
 
239
        b = WorkingTree.open_containing(u'.')[0].branch
295
240
 
296
241
        for rev in revs:
297
242
            revinfo = rev.in_history(b)
298
243
            if revinfo.revno is None:
299
 
                dotted_map = b.get_revision_id_to_revno_map()
300
 
                revno = '.'.join(str(i) for i in dotted_map[revinfo.rev_id])
301
 
                print '%s %s' % (revno, revinfo.rev_id)
 
244
                print '     %s' % revinfo.rev_id
302
245
            else:
303
246
                print '%4d %s' % (revinfo.revno, revinfo.rev_id)
304
247
 
323
266
 
324
267
    Adding a file whose parent directory is not versioned will
325
268
    implicitly add the parent, and so on up to the root. This means
326
 
    you should never need to explicitly add a directory, they'll just
 
269
    you should never need to explictly add a directory, they'll just
327
270
    get added when you add a file in the directory.
328
271
 
329
272
    --dry-run will show which files would be added, but not actually 
330
273
    add them.
331
 
 
332
 
    --file-ids-from will try to use the file ids from the supplied path.
333
 
    It looks up ids trying to find a matching parent directory with the
334
 
    same filename, and then by pure path. This option is rarely needed
335
 
    but can be useful when adding the same logical file into two
336
 
    branches that will be merged later (without showing the two different
337
 
    adds as a conflict). It is also useful when merging another project
338
 
    into a subdirectory of this one.
339
274
    """
340
275
    takes_args = ['file*']
341
 
    takes_options = ['no-recurse', 'dry-run', 'verbose',
342
 
                     Option('file-ids-from', type=unicode,
343
 
                            help='Lookup file ids from here')]
 
276
    takes_options = ['no-recurse', 'dry-run', 'verbose']
344
277
    encoding_type = 'replace'
345
 
    _see_also = ['remove']
346
278
 
347
 
    def run(self, file_list, no_recurse=False, dry_run=False, verbose=False,
348
 
            file_ids_from=None):
 
279
    def run(self, file_list, no_recurse=False, dry_run=False, verbose=False):
349
280
        import bzrlib.add
350
281
 
351
 
        base_tree = None
352
 
        if file_ids_from is not None:
353
 
            try:
354
 
                base_tree, base_path = WorkingTree.open_containing(
355
 
                                            file_ids_from)
356
 
            except errors.NoWorkingTree:
357
 
                base_branch, base_path = Branch.open_containing(
358
 
                                            file_ids_from)
359
 
                base_tree = base_branch.basis_tree()
360
 
 
361
 
            action = bzrlib.add.AddFromBaseAction(base_tree, base_path,
362
 
                          to_file=self.outf, should_print=(not is_quiet()))
363
 
        else:
364
 
            action = bzrlib.add.AddAction(to_file=self.outf,
365
 
                should_print=(not is_quiet()))
366
 
 
367
 
        if base_tree:
368
 
            base_tree.lock_read()
369
 
        try:
370
 
            file_list = self._maybe_expand_globs(file_list)
371
 
            if file_list:
372
 
                tree = WorkingTree.open_containing(file_list[0])[0]
373
 
            else:
374
 
                tree = WorkingTree.open_containing(u'.')[0]
375
 
            added, ignored = tree.smart_add(file_list, not
376
 
                no_recurse, action=action, save=not dry_run)
377
 
        finally:
378
 
            if base_tree is not None:
379
 
                base_tree.unlock()
 
282
        action = bzrlib.add.AddAction(to_file=self.outf,
 
283
            should_add=(not dry_run), should_print=(not is_quiet()))
 
284
 
 
285
        added, ignored = bzrlib.add.smart_add(file_list, not no_recurse, 
 
286
                                              action=action)
380
287
        if len(ignored) > 0:
381
288
            if verbose:
382
289
                for glob in sorted(ignored.keys()):
397
304
 
398
305
    This is equivalent to creating the directory and then adding it.
399
306
    """
400
 
 
401
307
    takes_args = ['dir+']
402
308
    encoding_type = 'replace'
403
309
 
406
312
            os.mkdir(d)
407
313
            wt, dd = WorkingTree.open_containing(d)
408
314
            wt.add([dd])
409
 
            self.outf.write('added %s\n' % d)
 
315
            print >>self.outf, 'added', d
410
316
 
411
317
 
412
318
class cmd_relpath(Command):
413
319
    """Show path of a file relative to root"""
414
 
 
415
320
    takes_args = ['filename']
416
321
    hidden = True
417
322
    
428
333
    """Show inventory of the current working copy or a revision.
429
334
 
430
335
    It is possible to limit the output to a particular entry
431
 
    type using the --kind option.  For example: --kind file.
432
 
 
433
 
    It is also possible to restrict the list of files to a specific
434
 
    set. For example: bzr inventory --show-ids this/file
 
336
    type using the --kind option.  For example; --kind file.
435
337
    """
436
 
 
437
 
    hidden = True
438
 
    _see_also = ['ls']
439
338
    takes_options = ['revision', 'show-ids', 'kind']
440
 
    takes_args = ['file*']
441
 
 
 
339
    
442
340
    @display_command
443
 
    def run(self, revision=None, show_ids=False, kind=None, file_list=None):
 
341
    def run(self, revision=None, show_ids=False, kind=None):
444
342
        if kind and kind not in ['file', 'directory', 'symlink']:
445
 
            raise errors.BzrCommandError('invalid kind specified')
446
 
 
447
 
        work_tree, file_list = tree_files(file_list)
448
 
        work_tree.lock_read()
449
 
        try:
450
 
            if revision is not None:
451
 
                if len(revision) > 1:
452
 
                    raise errors.BzrCommandError(
453
 
                        'bzr inventory --revision takes exactly one revision'
454
 
                        ' identifier')
455
 
                revision_id = revision[0].in_history(work_tree.branch).rev_id
456
 
                tree = work_tree.branch.repository.revision_tree(revision_id)
457
 
 
458
 
                extra_trees = [work_tree]
459
 
                tree.lock_read()
460
 
            else:
461
 
                tree = work_tree
462
 
                extra_trees = []
463
 
 
464
 
            if file_list is not None:
465
 
                file_ids = tree.paths2ids(file_list, trees=extra_trees,
466
 
                                          require_versioned=True)
467
 
                # find_ids_across_trees may include some paths that don't
468
 
                # exist in 'tree'.
469
 
                entries = sorted((tree.id2path(file_id), tree.inventory[file_id])
470
 
                                 for file_id in file_ids if file_id in tree)
471
 
            else:
472
 
                entries = tree.inventory.entries()
473
 
        finally:
474
 
            tree.unlock()
475
 
            if tree is not work_tree:
476
 
                work_tree.unlock()
477
 
 
478
 
        for path, entry in entries:
 
343
            raise BzrCommandError('invalid kind specified')
 
344
        tree = WorkingTree.open_containing(u'.')[0]
 
345
        if revision is None:
 
346
            inv = tree.read_working_inventory()
 
347
        else:
 
348
            if len(revision) > 1:
 
349
                raise BzrCommandError('bzr inventory --revision takes'
 
350
                    ' exactly one revision identifier')
 
351
            inv = tree.branch.repository.get_revision_inventory(
 
352
                revision[0].in_history(tree.branch).rev_id)
 
353
 
 
354
        for path, entry in inv.entries():
479
355
            if kind and kind != entry.kind:
480
356
                continue
481
357
            if show_ids:
494
370
 
495
371
    If the last argument is a versioned directory, all the other names
496
372
    are moved into it.  Otherwise, there must be exactly two arguments
497
 
    and the file is changed to a new name.
498
 
 
499
 
    If OLDNAME does not exist on the filesystem but is versioned and
500
 
    NEWNAME does exist on the filesystem but is not versioned, mv
501
 
    assumes that the file has been manually moved and only updates
502
 
    its internal inventory to reflect that change.
503
 
    The same is valid when moving many SOURCE files to a DESTINATION.
 
373
    and the file is changed to a new name, which must not already exist.
504
374
 
505
375
    Files cannot be moved between branches.
506
376
    """
507
 
 
508
377
    takes_args = ['names*']
509
 
    takes_options = [Option("after", help="move only the bzr identifier"
510
 
        " of the file (file has already been moved). Use this flag if"
511
 
        " bzr is not able to detect this itself.")]
512
378
    aliases = ['move', 'rename']
 
379
 
513
380
    encoding_type = 'replace'
514
381
 
515
 
    def run(self, names_list, after=False):
516
 
        if names_list is None:
517
 
            names_list = []
518
 
 
 
382
    def run(self, names_list):
519
383
        if len(names_list) < 2:
520
 
            raise errors.BzrCommandError("missing file argument")
 
384
            raise BzrCommandError("missing file argument")
521
385
        tree, rel_names = tree_files(names_list)
522
386
        
523
387
        if os.path.isdir(names_list[-1]):
524
388
            # move into existing directory
525
 
            for pair in tree.move(rel_names[:-1], rel_names[-1], after=after):
 
389
            for pair in tree.move(rel_names[:-1], rel_names[-1]):
526
390
                self.outf.write("%s => %s\n" % pair)
527
391
        else:
528
392
            if len(names_list) != 2:
529
 
                raise errors.BzrCommandError('to mv multiple files the'
530
 
                                             ' destination must be a versioned'
531
 
                                             ' directory')
532
 
            tree.rename_one(rel_names[0], rel_names[1], after=after)
 
393
                raise BzrCommandError('to mv multiple files the destination '
 
394
                                      'must be a versioned directory')
 
395
            tree.rename_one(rel_names[0], rel_names[1])
533
396
            self.outf.write("%s => %s\n" % (rel_names[0], rel_names[1]))
534
397
            
535
398
    
544
407
    from one into the other.  Once one branch has merged, the other should
545
408
    be able to pull it again.
546
409
 
 
410
    If branches have diverged, you can use 'bzr merge' to pull the text changes
 
411
    from one into the other.  Once one branch has merged, the other should
 
412
    be able to pull it again.
 
413
 
547
414
    If you want to forget your local changes and just update your branch to
548
415
    match the remote one, use pull --overwrite.
549
416
 
550
417
    If there is no default location set, the first pull will set it.  After
551
418
    that, you can omit the location to use the default.  To change the
552
 
    default, use --remember. The value will only be saved if the remote
553
 
    location can be accessed.
 
419
    default, use --remember.
554
420
    """
555
 
 
556
 
    _see_also = ['push', 'update', 'status-flags']
557
 
    takes_options = ['remember', 'overwrite', 'revision', 'verbose',
558
 
        Option('directory',
559
 
            help='branch to pull into, '
560
 
                 'rather than the one containing the working directory',
561
 
            short_name='d',
562
 
            type=unicode,
563
 
            ),
564
 
        ]
 
421
    takes_options = ['remember', 'overwrite', 'revision', 'verbose']
565
422
    takes_args = ['location?']
566
423
    encoding_type = 'replace'
567
424
 
568
 
    def run(self, location=None, remember=False, overwrite=False,
569
 
            revision=None, verbose=False,
570
 
            directory=None):
571
 
        from bzrlib.tag import _merge_tags_if_possible
 
425
    def run(self, location=None, remember=False, overwrite=False, revision=None, verbose=False):
572
426
        # FIXME: too much stuff is in the command class
573
 
        revision_id = None
574
 
        mergeable = None
575
 
        if directory is None:
576
 
            directory = u'.'
577
427
        try:
578
 
            tree_to = WorkingTree.open_containing(directory)[0]
 
428
            tree_to = WorkingTree.open_containing(u'.')[0]
579
429
            branch_to = tree_to.branch
580
 
        except errors.NoWorkingTree:
 
430
        except NoWorkingTree:
581
431
            tree_to = None
582
 
            branch_to = Branch.open_containing(directory)[0]
583
 
 
584
 
        reader = None
585
 
        if location is not None:
586
 
            try:
587
 
                mergeable = bundle.read_mergeable_from_url(
588
 
                    location)
589
 
            except errors.NotABundle:
590
 
                pass # Continue on considering this url a Branch
591
 
 
 
432
            branch_to = Branch.open_containing(u'.')[0]
592
433
        stored_loc = branch_to.get_parent()
593
434
        if location is None:
594
435
            if stored_loc is None:
595
 
                raise errors.BzrCommandError("No pull location known or"
596
 
                                             " specified.")
 
436
                raise BzrCommandError("No pull location known or specified.")
597
437
            else:
598
438
                display_url = urlutils.unescape_for_display(stored_loc,
599
439
                        self.outf.encoding)
600
440
                self.outf.write("Using saved location: %s\n" % display_url)
601
441
                location = stored_loc
602
442
 
603
 
        if mergeable is not None:
604
 
            if revision is not None:
605
 
                raise errors.BzrCommandError(
606
 
                    'Cannot use -r with merge directives or bundles')
607
 
            revision_id = mergeable.install_revisions(branch_to.repository)
608
 
            branch_from = branch_to
 
443
        branch_from = Branch.open(location)
 
444
 
 
445
        if branch_to.get_parent() is None or remember:
 
446
            branch_to.set_parent(branch_from.base)
 
447
 
 
448
        if revision is None:
 
449
            rev_id = None
 
450
        elif len(revision) == 1:
 
451
            rev_id = revision[0].in_history(branch_from).rev_id
609
452
        else:
610
 
            branch_from = Branch.open(location)
611
 
 
612
 
            if branch_to.get_parent() is None or remember:
613
 
                branch_to.set_parent(branch_from.base)
614
 
 
615
 
        if revision is not None:
616
 
            if len(revision) == 1:
617
 
                revision_id = revision[0].in_history(branch_from).rev_id
618
 
            else:
619
 
                raise errors.BzrCommandError(
620
 
                    'bzr pull --revision takes one value.')
 
453
            raise BzrCommandError('bzr pull --revision takes one value.')
621
454
 
622
455
        old_rh = branch_to.revision_history()
623
456
        if tree_to is not None:
624
 
            result = tree_to.pull(branch_from, overwrite, revision_id,
625
 
                delta._ChangeReporter(unversioned_filter=tree_to.is_ignored))
 
457
            count = tree_to.pull(branch_from, overwrite, rev_id)
626
458
        else:
627
 
            result = branch_to.pull(branch_from, overwrite, revision_id)
 
459
            count = branch_to.pull(branch_from, overwrite, rev_id)
 
460
        note('%d revision(s) pulled.' % (count,))
628
461
 
629
 
        result.report(self.outf)
630
462
        if verbose:
631
 
            from bzrlib.log import show_changed_revisions
632
463
            new_rh = branch_to.revision_history()
633
 
            show_changed_revisions(branch_to, old_rh, new_rh,
634
 
                                   to_file=self.outf)
 
464
            if old_rh != new_rh:
 
465
                # Something changed
 
466
                from bzrlib.log import show_changed_revisions
 
467
                show_changed_revisions(branch_to, old_rh, new_rh,
 
468
                                       to_file=self.outf)
635
469
 
636
470
 
637
471
class cmd_push(Command):
656
490
 
657
491
    If there is no default push location set, the first push will set it.
658
492
    After that, you can omit the location to use the default.  To change the
659
 
    default, use --remember. The value will only be saved if the remote
660
 
    location can be accessed.
 
493
    default, use --remember.
661
494
    """
662
 
 
663
 
    _see_also = ['pull', 'update', 'working-trees']
664
495
    takes_options = ['remember', 'overwrite', 'verbose',
665
 
        Option('create-prefix',
666
 
               help='Create the path leading up to the branch '
667
 
                    'if it does not already exist'),
668
 
        Option('directory',
669
 
            help='branch to push from, '
670
 
                 'rather than the one containing the working directory',
671
 
            short_name='d',
672
 
            type=unicode,
673
 
            ),
674
 
        Option('use-existing-dir',
675
 
               help='By default push will fail if the target'
676
 
                    ' directory exists, but does not already'
677
 
                    ' have a control directory. This flag will'
678
 
                    ' allow push to proceed.'),
679
 
        ]
 
496
                     Option('create-prefix', 
 
497
                            help='Create the path leading up to the branch '
 
498
                                 'if it does not already exist')]
680
499
    takes_args = ['location?']
681
500
    encoding_type = 'replace'
682
501
 
683
502
    def run(self, location=None, remember=False, overwrite=False,
684
 
            create_prefix=False, verbose=False,
685
 
            use_existing_dir=False,
686
 
            directory=None):
 
503
            create_prefix=False, verbose=False):
687
504
        # FIXME: Way too big!  Put this into a function called from the
688
505
        # command.
689
 
        if directory is None:
690
 
            directory = '.'
691
 
        br_from = Branch.open_containing(directory)[0]
 
506
        from bzrlib.transport import get_transport
 
507
        
 
508
        br_from = Branch.open_containing('.')[0]
692
509
        stored_loc = br_from.get_push_location()
693
510
        if location is None:
694
511
            if stored_loc is None:
695
 
                raise errors.BzrCommandError("No push location known or specified.")
 
512
                raise BzrCommandError("No push location known or specified.")
696
513
            else:
697
514
                display_url = urlutils.unescape_for_display(stored_loc,
698
515
                        self.outf.encoding)
699
 
                self.outf.write("Using saved location: %s\n" % display_url)
 
516
                self.outf.write("Using saved location: %s" % display_url)
700
517
                location = stored_loc
701
518
 
702
 
        to_transport = transport.get_transport(location)
 
519
        transport = get_transport(location)
 
520
        location_url = transport.base
 
521
        if br_from.get_push_location() is None or remember:
 
522
            br_from.set_push_location(location_url)
703
523
 
704
 
        br_to = repository_to = dir_to = None
705
 
        try:
706
 
            dir_to = bzrdir.BzrDir.open_from_transport(to_transport)
707
 
        except errors.NotBranchError:
708
 
            pass # Didn't find anything
709
 
        else:
710
 
            # If we can open a branch, use its direct repository, otherwise see
711
 
            # if there is a repository without a branch.
712
 
            try:
713
 
                br_to = dir_to.open_branch()
714
 
            except errors.NotBranchError:
715
 
                # Didn't find a branch, can we find a repository?
716
 
                try:
717
 
                    repository_to = dir_to.find_repository()
718
 
                except errors.NoRepositoryPresent:
719
 
                    pass
720
 
            else:
721
 
                # Found a branch, so we must have found a repository
722
 
                repository_to = br_to.repository
723
 
        push_result = None
724
524
        old_rh = []
725
 
        if dir_to is None:
726
 
            # The destination doesn't exist; create it.
727
 
            # XXX: Refactor the create_prefix/no_create_prefix code into a
728
 
            #      common helper function
729
 
            try:
730
 
                to_transport.mkdir('.')
731
 
            except errors.FileExists:
732
 
                if not use_existing_dir:
733
 
                    raise errors.BzrCommandError("Target directory %s"
734
 
                         " already exists, but does not have a valid .bzr"
735
 
                         " directory. Supply --use-existing-dir to push"
736
 
                         " there anyway." % location)
737
 
            except errors.NoSuchFile:
738
 
                if not create_prefix:
739
 
                    raise errors.BzrCommandError("Parent directory of %s"
740
 
                        " does not exist."
741
 
                        "\nYou may supply --create-prefix to create all"
742
 
                        " leading parent directories."
743
 
                        % location)
744
 
 
745
 
                _create_prefix(to_transport)
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_on_transport(to_transport,
 
525
        try:
 
526
            dir_to = bzrlib.bzrdir.BzrDir.open(location_url)
 
527
            br_to = dir_to.open_branch()
 
528
        except NotBranchError:
 
529
            # create a branch.
 
530
            transport = transport.clone('..')
 
531
            if not create_prefix:
 
532
                try:
 
533
                    relurl = transport.relpath(location_url)
 
534
                    mutter('creating directory %s => %s', location_url, relurl)
 
535
                    transport.mkdir(relurl)
 
536
                except NoSuchFile:
 
537
                    raise BzrCommandError("Parent directory of %s "
 
538
                                          "does not exist." % location)
 
539
            else:
 
540
                current = transport.base
 
541
                needed = [(transport, transport.relpath(location_url))]
 
542
                while needed:
 
543
                    try:
 
544
                        transport, relpath = needed[-1]
 
545
                        transport.mkdir(relpath)
 
546
                        needed.pop()
 
547
                    except NoSuchFile:
 
548
                        new_transport = transport.clone('..')
 
549
                        needed.append((new_transport,
 
550
                                       new_transport.relpath(transport.base)))
 
551
                        if new_transport.base == transport.base:
 
552
                            raise BzrCommandError("Could not create "
 
553
                                                  "path prefix.")
 
554
            dir_to = br_from.bzrdir.clone(location_url,
751
555
                revision_id=br_from.last_revision())
752
556
            br_to = dir_to.open_branch()
753
 
            # TODO: Some more useful message about what was copied
754
 
            note('Created new branch.')
755
 
            # We successfully created the target, remember it
756
 
            if br_from.get_push_location() is None or remember:
757
 
                br_from.set_push_location(br_to.base)
758
 
        elif repository_to is None:
759
 
            # we have a bzrdir but no branch or repository
760
 
            # XXX: Figure out what to do other than complain.
761
 
            raise errors.BzrCommandError("At %s you have a valid .bzr control"
762
 
                " directory, but not a branch or repository. This is an"
763
 
                " unsupported configuration. Please move the target directory"
764
 
                " out of the way and try again."
765
 
                % location)
766
 
        elif br_to is None:
767
 
            # We have a repository but no branch, copy the revisions, and then
768
 
            # create a branch.
769
 
            last_revision_id = br_from.last_revision()
770
 
            repository_to.fetch(br_from.repository,
771
 
                                revision_id=last_revision_id)
772
 
            br_to = br_from.clone(dir_to, revision_id=last_revision_id)
773
 
            note('Created new branch.')
774
 
            if br_from.get_push_location() is None or remember:
775
 
                br_from.set_push_location(br_to.base)
776
 
        else: # We have a valid to branch
777
 
            # We were able to connect to the remote location, so remember it
778
 
            # we don't need to successfully push because of possible divergence.
779
 
            if br_from.get_push_location() is None or remember:
780
 
                br_from.set_push_location(br_to.base)
 
557
            count = len(br_to.revision_history())
 
558
        else:
781
559
            old_rh = br_to.revision_history()
782
560
            try:
783
561
                try:
784
562
                    tree_to = dir_to.open_workingtree()
785
563
                except errors.NotLocalUrl:
786
 
                    warning("This transport does not update the working " 
787
 
                            "tree of: %s. See 'bzr help working-trees' for "
788
 
                            "more information." % br_to.base)
789
 
                    push_result = br_from.push(br_to, overwrite)
790
 
                except errors.NoWorkingTree:
791
 
                    push_result = br_from.push(br_to, overwrite)
 
564
                    warning('This transport does not update the working '
 
565
                            'tree of: %s' % (br_to.base,))
 
566
                    count = br_to.pull(br_from, overwrite)
 
567
                except NoWorkingTree:
 
568
                    count = br_to.pull(br_from, overwrite)
792
569
                else:
793
 
                    tree_to.lock_write()
794
 
                    try:
795
 
                        push_result = br_from.push(tree_to.branch, overwrite)
796
 
                        tree_to.update()
797
 
                    finally:
798
 
                        tree_to.unlock()
799
 
            except errors.DivergedBranches:
800
 
                raise errors.BzrCommandError('These branches have diverged.'
801
 
                                        '  Try using "merge" and then "push".')
802
 
        if push_result is not None:
803
 
            push_result.report(self.outf)
804
 
        elif verbose:
 
570
                    count = tree_to.pull(br_from, overwrite)
 
571
            except DivergedBranches:
 
572
                raise BzrCommandError("These branches have diverged."
 
573
                                      "  Try a merge then push with overwrite.")
 
574
        note('%d revision(s) pushed.' % (count,))
 
575
 
 
576
        if verbose:
805
577
            new_rh = br_to.revision_history()
806
578
            if old_rh != new_rh:
807
579
                # Something changed
808
580
                from bzrlib.log import show_changed_revisions
809
581
                show_changed_revisions(br_to, old_rh, new_rh,
810
582
                                       to_file=self.outf)
811
 
        else:
812
 
            # we probably did a clone rather than a push, so a message was
813
 
            # emitted above
814
 
            pass
815
583
 
816
584
 
817
585
class cmd_branch(Command):
819
587
 
820
588
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
821
589
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
822
 
    If the FROM_LOCATION has no / or path separator embedded, the TO_LOCATION
823
 
    is derived from the FROM_LOCATION by stripping a leading scheme or drive
824
 
    identifier, if any. For example, "branch lp:foo-bar" will attempt to
825
 
    create ./foo-bar.
826
590
 
827
591
    To retrieve the branch as of a particular revision, supply the --revision
828
592
    parameter, as in "branch foo/bar -r 5".
 
593
 
 
594
    --basis is to speed up branching from remote branches.  When specified, it
 
595
    copies all the file-contents, inventory and revision data from the basis
 
596
    branch before copying anything from the remote branch.
829
597
    """
830
 
 
831
 
    _see_also = ['checkout']
832
598
    takes_args = ['from_location', 'to_location?']
833
 
    takes_options = ['revision']
 
599
    takes_options = ['revision', 'basis']
834
600
    aliases = ['get', 'clone']
835
601
 
836
 
    def run(self, from_location, to_location=None, revision=None):
837
 
        from bzrlib.tag import _merge_tags_if_possible
 
602
    def run(self, from_location, to_location=None, revision=None, basis=None):
 
603
        from bzrlib.transport import get_transport
 
604
        from bzrlib.osutils import rmtree
838
605
        if revision is None:
839
606
            revision = [None]
840
607
        elif len(revision) > 1:
841
 
            raise errors.BzrCommandError(
 
608
            raise BzrCommandError(
842
609
                'bzr branch --revision takes exactly 1 revision value')
843
 
 
844
 
        br_from = Branch.open(from_location)
 
610
        try:
 
611
            br_from = Branch.open(from_location)
 
612
        except OSError, e:
 
613
            if e.errno == errno.ENOENT:
 
614
                raise BzrCommandError('Source location "%s" does not'
 
615
                                      ' exist.' % to_location)
 
616
            else:
 
617
                raise
845
618
        br_from.lock_read()
846
619
        try:
 
620
            if basis is not None:
 
621
                basis_dir = bzrdir.BzrDir.open_containing(basis)[0]
 
622
            else:
 
623
                basis_dir = None
847
624
            if len(revision) == 1 and revision[0] is not None:
848
625
                revision_id = revision[0].in_history(br_from)[1]
849
626
            else:
852
629
                # RBC 20060209
853
630
                revision_id = br_from.last_revision()
854
631
            if to_location is None:
855
 
                to_location = urlutils.derive_to_location(from_location)
 
632
                to_location = os.path.basename(from_location.rstrip("/\\"))
856
633
                name = None
857
634
            else:
858
635
                name = os.path.basename(to_location) + '\n'
859
636
 
860
 
            to_transport = transport.get_transport(to_location)
 
637
            to_transport = get_transport(to_location)
861
638
            try:
862
639
                to_transport.mkdir('.')
863
 
            except errors.FileExists:
864
 
                raise errors.BzrCommandError('Target directory "%s" already'
865
 
                                             ' exists.' % to_location)
866
 
            except errors.NoSuchFile:
867
 
                raise errors.BzrCommandError('Parent of "%s" does not exist.'
868
 
                                             % to_location)
 
640
            except bzrlib.errors.FileExists:
 
641
                raise BzrCommandError('Target directory "%s" already'
 
642
                                      ' exists.' % to_location)
 
643
            except bzrlib.errors.NoSuchFile:
 
644
                raise BzrCommandError('Parent of "%s" does not exist.' %
 
645
                                      to_location)
869
646
            try:
870
647
                # preserve whatever source format we have.
871
 
                dir = br_from.bzrdir.sprout(to_transport.base, revision_id)
 
648
                dir = br_from.bzrdir.sprout(to_transport.base,
 
649
                        revision_id, basis_dir)
872
650
                branch = dir.open_branch()
873
 
            except errors.NoSuchRevision:
874
 
                to_transport.delete_tree('.')
 
651
            except bzrlib.errors.NoSuchRevision:
 
652
                # TODO: jam 20060426 This only works on local paths
 
653
                #       and it would be nice if 'bzr branch' could
 
654
                #       work on a remote path
 
655
                rmtree(to_location)
875
656
                msg = "The branch %s has no revision %s." % (from_location, revision[0])
876
 
                raise errors.BzrCommandError(msg)
 
657
                raise BzrCommandError(msg)
 
658
            except bzrlib.errors.UnlistableBranch:
 
659
                rmtree(to_location)
 
660
                msg = "The branch %s cannot be used as a --basis" % (basis,)
 
661
                raise BzrCommandError(msg)
877
662
            if name:
878
663
                branch.control_files.put_utf8('branch-name', name)
879
 
            _merge_tags_if_possible(br_from, branch)
880
664
            note('Branched %d revision(s).' % branch.revno())
881
665
        finally:
882
666
            br_from.unlock()
892
676
    
893
677
    If the TO_LOCATION is omitted, the last component of the BRANCH_LOCATION will
894
678
    be used.  In other words, "checkout ../foo/bar" will attempt to create ./bar.
895
 
    If the BRANCH_LOCATION has no / or path separator embedded, the TO_LOCATION
896
 
    is derived from the BRANCH_LOCATION by stripping a leading scheme or drive
897
 
    identifier, if any. For example, "checkout lp:foo-bar" will attempt to
898
 
    create ./foo-bar.
899
679
 
900
680
    To retrieve the branch as of a particular revision, supply the --revision
901
681
    parameter, as in "checkout foo/bar -r 5". Note that this will be immediately
902
682
    out of date [so you cannot commit] but it may be useful (i.e. to examine old
903
683
    code.)
 
684
 
 
685
    --basis is to speed up checking out from remote branches.  When specified, it
 
686
    uses the inventory and file contents from the basis branch in preference to the
 
687
    branch being checked out.
904
688
    """
905
 
 
906
 
    _see_also = ['checkouts', 'branch']
907
689
    takes_args = ['branch_location?', 'to_location?']
908
 
    takes_options = ['revision',
 
690
    takes_options = ['revision', # , 'basis']
909
691
                     Option('lightweight',
910
692
                            help="perform a lightweight checkout. Lightweight "
911
693
                                 "checkouts depend on access to the branch for "
914
696
                                 "such access, and also support local commits."
915
697
                            ),
916
698
                     ]
917
 
    aliases = ['co']
918
699
 
919
 
    def run(self, branch_location=None, to_location=None, revision=None,
 
700
    def run(self, branch_location=None, to_location=None, revision=None, basis=None,
920
701
            lightweight=False):
921
702
        if revision is None:
922
703
            revision = [None]
923
704
        elif len(revision) > 1:
924
 
            raise errors.BzrCommandError(
 
705
            raise BzrCommandError(
925
706
                'bzr checkout --revision takes exactly 1 revision value')
926
707
        if branch_location is None:
927
 
            branch_location = osutils.getcwd()
 
708
            branch_location = bzrlib.osutils.getcwd()
928
709
            to_location = branch_location
929
710
        source = Branch.open(branch_location)
930
711
        if len(revision) == 1 and revision[0] is not None:
932
713
        else:
933
714
            revision_id = None
934
715
        if to_location is None:
935
 
            to_location = urlutils.derive_to_location(branch_location)
 
716
            to_location = os.path.basename(branch_location.rstrip("/\\"))
936
717
        # if the source and to_location are the same, 
937
718
        # and there is no working tree,
938
719
        # then reconstitute a branch
939
 
        if (osutils.abspath(to_location) ==
940
 
            osutils.abspath(branch_location)):
 
720
        if (bzrlib.osutils.abspath(to_location) == 
 
721
            bzrlib.osutils.abspath(branch_location)):
941
722
            try:
942
723
                source.bzrdir.open_workingtree()
943
724
            except errors.NoWorkingTree:
947
728
            os.mkdir(to_location)
948
729
        except OSError, e:
949
730
            if e.errno == errno.EEXIST:
950
 
                raise errors.BzrCommandError('Target directory "%s" already'
951
 
                                             ' exists.' % to_location)
 
731
                raise BzrCommandError('Target directory "%s" already'
 
732
                                      ' exists.' % to_location)
952
733
            if e.errno == errno.ENOENT:
953
 
                raise errors.BzrCommandError('Parent of "%s" does not exist.'
954
 
                                             % to_location)
 
734
                raise BzrCommandError('Parent of "%s" does not exist.' %
 
735
                                      to_location)
955
736
            else:
956
737
                raise
957
 
        source.create_checkout(to_location, revision_id, lightweight)
 
738
        old_format = bzrlib.bzrdir.BzrDirFormat.get_default_format()
 
739
        bzrlib.bzrdir.BzrDirFormat.set_default_format(bzrdir.BzrDirMetaFormat1())
 
740
        try:
 
741
            if lightweight:
 
742
                checkout = bzrdir.BzrDirMetaFormat1().initialize(to_location)
 
743
                bzrlib.branch.BranchReferenceFormat().initialize(checkout, source)
 
744
            else:
 
745
                checkout_branch =  bzrlib.bzrdir.BzrDir.create_branch_convenience(
 
746
                    to_location, force_new_tree=False)
 
747
                checkout = checkout_branch.bzrdir
 
748
                checkout_branch.bind(source)
 
749
                if revision_id is not None:
 
750
                    rh = checkout_branch.revision_history()
 
751
                    checkout_branch.set_revision_history(rh[:rh.index(revision_id) + 1])
 
752
            checkout.create_workingtree(revision_id)
 
753
        finally:
 
754
            bzrlib.bzrdir.BzrDirFormat.set_default_format(old_format)
958
755
 
959
756
 
960
757
class cmd_renames(Command):
963
760
    # TODO: Option to show renames between two historical versions.
964
761
 
965
762
    # TODO: Only show renames under dir, rather than in the whole branch.
966
 
    _see_also = ['status']
967
763
    takes_args = ['dir?']
968
764
 
969
765
    @display_command
970
766
    def run(self, dir=u'.'):
971
767
        tree = WorkingTree.open_containing(dir)[0]
972
 
        tree.lock_read()
973
 
        try:
974
 
            new_inv = tree.inventory
975
 
            old_tree = tree.basis_tree()
976
 
            old_tree.lock_read()
977
 
            try:
978
 
                old_inv = old_tree.inventory
979
 
                renames = list(_mod_tree.find_renames(old_inv, new_inv))
980
 
                renames.sort()
981
 
                for old_name, new_name in renames:
982
 
                    self.outf.write("%s => %s\n" % (old_name, new_name))
983
 
            finally:
984
 
                old_tree.unlock()
985
 
        finally:
986
 
            tree.unlock()
 
768
        old_inv = tree.basis_tree().inventory
 
769
        new_inv = tree.read_working_inventory()
 
770
 
 
771
        renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
 
772
        renames.sort()
 
773
        for old_name, new_name in renames:
 
774
            self.outf.write("%s => %s\n" % (old_name, new_name))
987
775
 
988
776
 
989
777
class cmd_update(Command):
996
784
    If you want to discard your local changes, you can just do a 
997
785
    'bzr revert' instead of 'bzr commit' after the update.
998
786
    """
999
 
 
1000
 
    _see_also = ['pull', 'working-trees']
1001
787
    takes_args = ['dir?']
1002
 
    aliases = ['up']
1003
788
 
1004
789
    def run(self, dir='.'):
1005
790
        tree = WorkingTree.open_containing(dir)[0]
1006
 
        master = tree.branch.get_master_branch()
1007
 
        if master is not None:
1008
 
            tree.lock_write()
1009
 
        else:
1010
 
            tree.lock_tree_write()
 
791
        tree.lock_write()
1011
792
        try:
1012
 
            existing_pending_merges = tree.get_parent_ids()[1:]
1013
 
            last_rev = tree.last_revision()
1014
 
            if last_rev == tree.branch.last_revision():
 
793
            if tree.last_revision() == tree.branch.last_revision():
1015
794
                # may be up to date, check master too.
1016
795
                master = tree.branch.get_master_branch()
1017
 
                if master is None or last_rev == master.last_revision():
1018
 
                    revno = tree.branch.revision_id_to_revno(last_rev)
1019
 
                    note("Tree is up to date at revision %d." % (revno,))
1020
 
                    return 0
1021
 
            conflicts = tree.update(delta._ChangeReporter(
1022
 
                                        unversioned_filter=tree.is_ignored))
1023
 
            revno = tree.branch.revision_id_to_revno(tree.last_revision())
1024
 
            note('Updated to revision %d.' % (revno,))
1025
 
            if tree.get_parent_ids()[1:] != existing_pending_merges:
1026
 
                note('Your local commits will now show as pending merges with '
1027
 
                     "'bzr status', and can be committed with 'bzr commit'.")
 
796
                if master is None or master.last_revision == tree.last_revision():
 
797
                    note("Tree is up to date.")
 
798
                    return
 
799
            conflicts = tree.update()
 
800
            note('Updated to revision %d.' %
 
801
                 (tree.branch.revision_id_to_revno(tree.last_revision()),))
1028
802
            if conflicts != 0:
1029
803
                return 1
1030
804
            else:
1042
816
 
1043
817
    Branches and working trees will also report any missing revisions.
1044
818
    """
1045
 
    _see_also = ['revno', 'working-trees', 'repositories']
1046
819
    takes_args = ['location?']
1047
820
    takes_options = ['verbose']
1048
821
 
1049
822
    @display_command
1050
 
    def run(self, location=None, verbose=0):
 
823
    def run(self, location=None, verbose=False):
1051
824
        from bzrlib.info import show_bzrdir_info
1052
825
        show_bzrdir_info(bzrdir.BzrDir.open_containing(location)[0],
1053
826
                         verbose=verbose)
1054
827
 
1055
828
 
1056
829
class cmd_remove(Command):
1057
 
    """Remove files or directories.
 
830
    """Make a file unversioned.
1058
831
 
1059
 
    This makes bzr stop tracking changes to the specified files and
1060
 
    delete them if they can easily be recovered using revert.
 
832
    This makes bzr stop tracking changes to a versioned file.  It does
 
833
    not delete the working copy.
1061
834
 
1062
835
    You can specify one or more files, and/or --new.  If you specify --new,
1063
836
    only 'added' files will be removed.  If you specify both, then new files
1065
838
    also new, they will also be removed.
1066
839
    """
1067
840
    takes_args = ['file*']
1068
 
    takes_options = ['verbose',
1069
 
        Option('new', help='remove newly-added files'),
1070
 
        RegistryOption.from_kwargs('file-deletion-strategy',
1071
 
            'The file deletion mode to be used',
1072
 
            title='Deletion Strategy', value_switches=True, enum_switch=False,
1073
 
            safe='Only delete files if they can be'
1074
 
                 ' safely recovered (default).',
1075
 
            keep="Don't delete any files.",
1076
 
            force='Delete all the specified files, even if they can not be '
1077
 
                'recovered and even if they are non-empty directories.')]
 
841
    takes_options = ['verbose', Option('new', help='remove newly-added files')]
1078
842
    aliases = ['rm']
1079
843
    encoding_type = 'replace'
1080
 
 
1081
 
    def run(self, file_list, verbose=False, new=False,
1082
 
        file_deletion_strategy='safe'):
 
844
    
 
845
    def run(self, file_list, verbose=False, new=False):
1083
846
        tree, file_list = tree_files(file_list)
1084
 
 
1085
 
        if file_list is not None:
1086
 
            file_list = [f for f in file_list if f != '']
1087
 
        elif not new:
1088
 
            raise errors.BzrCommandError('Specify one or more files to'
1089
 
            ' remove, or use --new.')
1090
 
 
1091
 
        if new:
1092
 
            added = tree.changes_from(tree.basis_tree(),
1093
 
                specific_files=file_list).added
1094
 
            file_list = sorted([f[0] for f in added], reverse=True)
 
847
        if new is False:
 
848
            if file_list is None:
 
849
                raise BzrCommandError('Specify one or more files to remove, or'
 
850
                                      ' use --new.')
 
851
        else:
 
852
            from bzrlib.delta import compare_trees
 
853
            added = [compare_trees(tree.basis_tree(), tree,
 
854
                                   specific_files=file_list).added]
 
855
            file_list = sorted([f[0] for f in added[0]], reverse=True)
1095
856
            if len(file_list) == 0:
1096
 
                raise errors.BzrCommandError('No matching files.')
1097
 
        tree.remove(file_list, verbose=verbose, to_file=self.outf,
1098
 
            keep_files=file_deletion_strategy=='keep',
1099
 
            force=file_deletion_strategy=='force')
 
857
                raise BzrCommandError('No matching files.')
 
858
        tree.remove(file_list, verbose=verbose, to_file=self.outf)
1100
859
 
1101
860
 
1102
861
class cmd_file_id(Command):
1106
865
    same through all revisions where the file exists, even when it is
1107
866
    moved or renamed.
1108
867
    """
1109
 
 
1110
868
    hidden = True
1111
 
    _see_also = ['inventory', 'ls']
1112
869
    takes_args = ['filename']
1113
870
 
1114
871
    @display_command
1115
872
    def run(self, filename):
1116
873
        tree, relpath = WorkingTree.open_containing(filename)
1117
 
        i = tree.path2id(relpath)
1118
 
        if i is None:
1119
 
            raise errors.NotVersionedError(filename)
 
874
        i = tree.inventory.path2id(relpath)
 
875
        if i == None:
 
876
            raise BzrError("%r is not a versioned file" % filename)
1120
877
        else:
1121
 
            self.outf.write(i + '\n')
 
878
            self.outf.write(i)
 
879
            self.outf.write('\n')
1122
880
 
1123
881
 
1124
882
class cmd_file_path(Command):
1127
885
    This prints one line for each directory down to the target,
1128
886
    starting at the branch root.
1129
887
    """
1130
 
 
1131
888
    hidden = True
1132
889
    takes_args = ['filename']
1133
890
 
1134
891
    @display_command
1135
892
    def run(self, filename):
1136
893
        tree, relpath = WorkingTree.open_containing(filename)
1137
 
        fid = tree.path2id(relpath)
1138
 
        if fid is None:
1139
 
            raise errors.NotVersionedError(filename)
1140
 
        segments = osutils.splitpath(relpath)
1141
 
        for pos in range(1, len(segments) + 1):
1142
 
            path = osutils.joinpath(segments[:pos])
1143
 
            self.outf.write("%s\n" % tree.path2id(path))
 
894
        inv = tree.inventory
 
895
        fid = inv.path2id(relpath)
 
896
        if fid == None:
 
897
            raise BzrError("%r is not a versioned file" % filename)
 
898
        for fip in inv.get_idpath(fid):
 
899
            self.outf.write(fip)
 
900
            self.outf.write('\n')
1144
901
 
1145
902
 
1146
903
class cmd_reconcile(Command):
1161
918
 
1162
919
    The branch *MUST* be on a listable system such as local disk or sftp.
1163
920
    """
1164
 
 
1165
 
    _see_also = ['check']
1166
921
    takes_args = ['branch?']
1167
922
 
1168
923
    def run(self, branch="."):
1169
924
        from bzrlib.reconcile import reconcile
1170
 
        dir = bzrdir.BzrDir.open(branch)
 
925
        dir = bzrlib.bzrdir.BzrDir.open(branch)
1171
926
        reconcile(dir)
1172
927
 
1173
928
 
1174
929
class cmd_revision_history(Command):
1175
 
    """Display the list of revision ids on a branch."""
1176
 
 
1177
 
    _see_also = ['log']
1178
 
    takes_args = ['location?']
1179
 
 
 
930
    """Display list of revision ids on this branch."""
1180
931
    hidden = True
1181
932
 
1182
933
    @display_command
1183
 
    def run(self, location="."):
1184
 
        branch = Branch.open_containing(location)[0]
1185
 
        for revid in branch.revision_history():
1186
 
            self.outf.write(revid)
 
934
    def run(self):
 
935
        branch = WorkingTree.open_containing(u'.')[0].branch
 
936
        for patchid in branch.revision_history():
 
937
            self.outf.write(patchid)
1187
938
            self.outf.write('\n')
1188
939
 
1189
940
 
1190
941
class cmd_ancestry(Command):
1191
942
    """List all revisions merged into this branch."""
1192
 
 
1193
 
    _see_also = ['log', 'revision-history']
1194
 
    takes_args = ['location?']
1195
 
 
1196
943
    hidden = True
1197
944
 
1198
945
    @display_command
1199
 
    def run(self, location="."):
1200
 
        try:
1201
 
            wt = WorkingTree.open_containing(location)[0]
1202
 
        except errors.NoWorkingTree:
1203
 
            b = Branch.open(location)
1204
 
            last_revision = b.last_revision()
1205
 
        else:
1206
 
            b = wt.branch
1207
 
            last_revision = wt.last_revision()
1208
 
 
1209
 
        revision_ids = b.repository.get_ancestry(last_revision)
1210
 
        assert revision_ids[0] is None
 
946
    def run(self):
 
947
        tree = WorkingTree.open_containing(u'.')[0]
 
948
        b = tree.branch
 
949
        # FIXME. should be tree.last_revision
 
950
        revision_ids = b.repository.get_ancestry(b.last_revision())
 
951
        assert revision_ids[0] == None
1211
952
        revision_ids.pop(0)
1212
953
        for revision_id in revision_ids:
1213
954
            self.outf.write(revision_id + '\n')
1221
962
 
1222
963
    If there is a repository in a parent directory of the location, then 
1223
964
    the history of the branch will be stored in the repository.  Otherwise
1224
 
    init creates a standalone branch which carries its own history
1225
 
    in the .bzr directory.
 
965
    init creates a standalone branch which carries its own history in 
 
966
    .bzr.
1226
967
 
1227
968
    If there is already a branch at the location but it has no working tree,
1228
969
    the tree can be populated with 'bzr checkout'.
1234
975
        bzr status
1235
976
        bzr commit -m 'imported project'
1236
977
    """
1237
 
 
1238
 
    _see_also = ['init-repo', 'branch', 'checkout']
1239
978
    takes_args = ['location?']
1240
979
    takes_options = [
1241
 
        Option('create-prefix',
1242
 
               help='Create the path leading up to the branch '
1243
 
                    'if it does not already exist'),
1244
 
         RegistryOption('format',
1245
 
                help='Specify a format for this branch. '
1246
 
                'See "help formats".',
1247
 
                registry=bzrdir.format_registry,
1248
 
                converter=bzrdir.format_registry.make_bzrdir,
1249
 
                value_switches=True,
1250
 
                title="Branch Format",
1251
 
                ),
1252
 
         Option('append-revisions-only',
1253
 
                help='Never change revnos or the existing log.'
1254
 
                '  Append revisions to it only.')
1255
 
         ]
1256
 
    def run(self, location=None, format=None, append_revisions_only=False,
1257
 
            create_prefix=False):
 
980
                     Option('format', 
 
981
                            help='Specify a format for this branch. Current'
 
982
                                 ' formats are: default, knit, metaweave and'
 
983
                                 ' weave. Default is knit; metaweave and'
 
984
                                 ' weave are deprecated',
 
985
                            type=get_format_type),
 
986
                     ]
 
987
    def run(self, location=None, format=None):
 
988
        from bzrlib.branch import Branch
1258
989
        if format is None:
1259
 
            format = bzrdir.format_registry.make_bzrdir('default')
 
990
            format = get_format_type('default')
1260
991
        if location is None:
1261
992
            location = u'.'
1262
 
 
1263
 
        to_transport = transport.get_transport(location)
1264
 
 
1265
 
        # The path has to exist to initialize a
1266
 
        # branch inside of it.
1267
 
        # Just using os.mkdir, since I don't
1268
 
        # believe that we want to create a bunch of
1269
 
        # locations if the user supplies an extended path
1270
 
        try:
1271
 
            to_transport.ensure_base()
1272
 
        except errors.NoSuchFile:
1273
 
            if not create_prefix:
1274
 
                raise errors.BzrCommandError("Parent directory of %s"
1275
 
                    " does not exist."
1276
 
                    "\nYou may supply --create-prefix to create all"
1277
 
                    " leading parent directories."
1278
 
                    % location)
1279
 
            _create_prefix(to_transport)
1280
 
 
 
993
        else:
 
994
            # The path has to exist to initialize a
 
995
            # branch inside of it.
 
996
            # Just using os.mkdir, since I don't
 
997
            # believe that we want to create a bunch of
 
998
            # locations if the user supplies an extended path
 
999
            if not os.path.exists(location):
 
1000
                os.mkdir(location)
1281
1001
        try:
1282
1002
            existing_bzrdir = bzrdir.BzrDir.open(location)
1283
 
        except errors.NotBranchError:
 
1003
        except NotBranchError:
1284
1004
            # really a NotBzrDir error...
1285
 
            branch = bzrdir.BzrDir.create_branch_convenience(to_transport.base,
1286
 
                                                             format=format)
 
1005
            bzrdir.BzrDir.create_branch_convenience(location, format=format)
1287
1006
        else:
1288
 
            from bzrlib.transport.local import LocalTransport
1289
1007
            if existing_bzrdir.has_branch():
1290
 
                if (isinstance(to_transport, LocalTransport)
1291
 
                    and not existing_bzrdir.has_workingtree()):
1292
 
                        raise errors.BranchExistsWithoutWorkingTree(location)
1293
 
                raise errors.AlreadyBranchError(location)
 
1008
                if existing_bzrdir.has_workingtree():
 
1009
                    raise errors.AlreadyBranchError(location)
 
1010
                else:
 
1011
                    raise errors.BranchExistsWithoutWorkingTree(location)
1294
1012
            else:
1295
 
                branch = existing_bzrdir.create_branch()
 
1013
                existing_bzrdir.create_branch()
1296
1014
                existing_bzrdir.create_workingtree()
1297
 
        if append_revisions_only:
1298
 
            try:
1299
 
                branch.set_append_revisions_only(True)
1300
 
            except errors.UpgradeRequired:
1301
 
                raise errors.BzrCommandError('This branch format cannot be set'
1302
 
                    ' to append-revisions-only.  Try --experimental-branch6')
1303
1015
 
1304
1016
 
1305
1017
class cmd_init_repository(Command):
1306
1018
    """Create a shared repository to hold branches.
1307
1019
 
1308
 
    New branches created under the repository directory will store their
1309
 
    revisions in the repository, not in the branch directory.
1310
 
 
1311
 
    If the --no-trees option is used then the branches in the repository
1312
 
    will not have working trees by default.
 
1020
    New branches created under the repository directory will store their revisions
 
1021
    in the repository, not in the branch directory, if the branch format supports
 
1022
    shared storage.
1313
1023
 
1314
1024
    example:
1315
 
        bzr init-repo --no-trees repo
 
1025
        bzr init-repo repo
1316
1026
        bzr init repo/trunk
1317
1027
        bzr checkout --lightweight repo/trunk trunk-checkout
1318
1028
        cd trunk-checkout
1319
1029
        (add files here)
1320
 
 
1321
 
    See 'bzr help repositories' for more information.
1322
1030
    """
1323
 
 
1324
 
    _see_also = ['init', 'branch', 'checkout']
1325
 
    takes_args = ["location"]
1326
 
    takes_options = [RegistryOption('format',
1327
 
                            help='Specify a format for this repository. See'
1328
 
                                 ' "bzr help formats" for details',
1329
 
                            registry=bzrdir.format_registry,
1330
 
                            converter=bzrdir.format_registry.make_bzrdir,
1331
 
                            value_switches=True, title='Repository format'),
1332
 
                     Option('no-trees',
1333
 
                             help='Branches in the repository will default to'
1334
 
                                  ' not having a working tree'),
1335
 
                    ]
 
1031
    takes_args = ["location"] 
 
1032
    takes_options = [Option('format', 
 
1033
                            help='Specify a format for this repository.'
 
1034
                                 ' Current formats are: default, knit,'
 
1035
                                 ' metaweave and weave. Default is knit;'
 
1036
                                 ' metaweave and weave are deprecated',
 
1037
                            type=get_format_type),
 
1038
                     Option('trees',
 
1039
                             help='Allows branches in repository to have'
 
1040
                             ' a working tree')]
1336
1041
    aliases = ["init-repo"]
1337
 
 
1338
 
    def run(self, location, format=None, no_trees=False):
 
1042
    def run(self, location, format=None, trees=False):
 
1043
        from bzrlib.transport import get_transport
1339
1044
        if format is None:
1340
 
            format = bzrdir.format_registry.make_bzrdir('default')
1341
 
 
1342
 
        if location is None:
1343
 
            location = '.'
1344
 
 
1345
 
        to_transport = transport.get_transport(location)
1346
 
        to_transport.ensure_base()
1347
 
 
1348
 
        newdir = format.initialize_on_transport(to_transport)
 
1045
            format = get_format_type('default')
 
1046
        transport = get_transport(location)
 
1047
        if not transport.has('.'):
 
1048
            transport.mkdir('')
 
1049
        newdir = format.initialize_on_transport(transport)
1349
1050
        repo = newdir.create_repository(shared=True)
1350
 
        repo.set_make_working_trees(not no_trees)
 
1051
        repo.set_make_working_trees(trees)
1351
1052
 
1352
1053
 
1353
1054
class cmd_diff(Command):
1354
 
    """Show differences in the working tree or between revisions.
 
1055
    """Show differences in working tree.
1355
1056
    
1356
1057
    If files are listed, only the changes in those files are listed.
1357
1058
    Otherwise, all changes for the tree are listed.
1361
1062
 
1362
1063
    examples:
1363
1064
        bzr diff
1364
 
            Shows the difference in the working tree versus the last commit
1365
1065
        bzr diff -r1
1366
 
            Difference between the working tree and revision 1
1367
1066
        bzr diff -r1..2
1368
 
            Difference between revision 2 and revision 1
1369
 
        bzr diff --prefix old/:new/
1370
 
            Same as 'bzr diff' but prefix paths with old/ and new/
 
1067
        bzr diff --diff-prefix old/:new/
1371
1068
        bzr diff bzr.mine bzr.dev
1372
 
            Show the differences between the two working trees
1373
1069
        bzr diff foo.c
1374
 
            Show just the differences for 'foo.c'
1375
1070
    """
1376
1071
    # TODO: Option to use external diff command; could be GNU diff, wdiff,
1377
1072
    #       or a graphical diff.
1383
1078
    #       deleted files.
1384
1079
 
1385
1080
    # TODO: This probably handles non-Unix newlines poorly.
1386
 
 
1387
 
    _see_also = ['status']
 
1081
    
1388
1082
    takes_args = ['file*']
1389
 
    takes_options = ['revision', 'diff-options',
1390
 
        Option('prefix', type=str,
1391
 
               short_name='p',
1392
 
               help='Set prefixes to added to old and new filenames, as '
1393
 
                    'two values separated by a colon. (eg "old/:new/")'),
1394
 
        ]
 
1083
    takes_options = ['revision', 'diff-options', 'prefix']
1395
1084
    aliases = ['di', 'dif']
1396
1085
    encoding_type = 'exact'
1397
1086
 
1407
1096
        elif prefix == '1':
1408
1097
            old_label = 'old/'
1409
1098
            new_label = 'new/'
1410
 
        elif ':' in prefix:
 
1099
        else:
 
1100
            if not ':' in prefix:
 
1101
                 raise BzrError("--diff-prefix expects two values separated by a colon")
1411
1102
            old_label, new_label = prefix.split(":")
1412
 
        else:
1413
 
            raise errors.BzrCommandError(
1414
 
                '--prefix expects two values separated by a colon'
1415
 
                ' (eg "old/:new/")')
1416
 
 
1417
 
        if revision and len(revision) > 2:
1418
 
            raise errors.BzrCommandError('bzr diff --revision takes exactly'
1419
 
                                         ' one or two revision specifiers')
1420
 
 
 
1103
        
1421
1104
        try:
1422
1105
            tree1, file_list = internal_tree_files(file_list)
1423
1106
            tree2 = None
1424
1107
            b = None
1425
1108
            b2 = None
1426
 
        except errors.FileInWrongBranch:
 
1109
        except FileInWrongBranch:
1427
1110
            if len(file_list) != 2:
1428
 
                raise errors.BzrCommandError("Files are in different branches")
 
1111
                raise BzrCommandError("Files are in different branches")
1429
1112
 
1430
1113
            tree1, file1 = WorkingTree.open_containing(file_list[0])
1431
1114
            tree2, file2 = WorkingTree.open_containing(file_list[1])
1432
1115
            if file1 != "" or file2 != "":
1433
1116
                # FIXME diff those two files. rbc 20051123
1434
 
                raise errors.BzrCommandError("Files are in different branches")
 
1117
                raise BzrCommandError("Files are in different branches")
1435
1118
            file_list = None
1436
 
        except errors.NotBranchError:
1437
 
            if (revision is not None and len(revision) == 2
1438
 
                and not revision[0].needs_branch()
1439
 
                and not revision[1].needs_branch()):
1440
 
                # If both revision specs include a branch, we can
1441
 
                # diff them without needing a local working tree
1442
 
                tree1, tree2 = None, None
1443
 
            else:
1444
 
                raise
1445
 
 
1446
 
        if tree2 is not None:
1447
 
            if revision is not None:
1448
 
                # FIXME: but there should be a clean way to diff between
1449
 
                # non-default versions of two trees, it's not hard to do
1450
 
                # internally...
1451
 
                raise errors.BzrCommandError(
1452
 
                        "Sorry, diffing arbitrary revisions across branches "
1453
 
                        "is not implemented yet")
1454
 
            return show_diff_trees(tree1, tree2, sys.stdout, 
1455
 
                                   specific_files=file_list,
1456
 
                                   external_diff_options=diff_options,
1457
 
                                   old_label=old_label, new_label=new_label)
1458
 
 
1459
 
        return diff_cmd_helper(tree1, file_list, diff_options,
1460
 
                               revision_specs=revision,
1461
 
                               old_label=old_label, new_label=new_label)
 
1119
        if revision is not None:
 
1120
            if tree2 is not None:
 
1121
                raise BzrCommandError("Can't specify -r with two branches")
 
1122
            if (len(revision) == 1) or (revision[1].spec is None):
 
1123
                return diff_cmd_helper(tree1, file_list, diff_options,
 
1124
                                       revision[0], 
 
1125
                                       old_label=old_label, new_label=new_label)
 
1126
            elif len(revision) == 2:
 
1127
                return diff_cmd_helper(tree1, file_list, diff_options,
 
1128
                                       revision[0], revision[1],
 
1129
                                       old_label=old_label, new_label=new_label)
 
1130
            else:
 
1131
                raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
 
1132
        else:
 
1133
            if tree2 is not None:
 
1134
                return show_diff_trees(tree1, tree2, sys.stdout, 
 
1135
                                       specific_files=file_list,
 
1136
                                       external_diff_options=diff_options,
 
1137
                                       old_label=old_label, new_label=new_label)
 
1138
            else:
 
1139
                return diff_cmd_helper(tree1, file_list, diff_options,
 
1140
                                       old_label=old_label, new_label=new_label)
1462
1141
 
1463
1142
 
1464
1143
class cmd_deleted(Command):
1470
1149
    # directories with readdir, rather than stating each one.  Same
1471
1150
    # level of effort but possibly much less IO.  (Or possibly not,
1472
1151
    # if the directories are very large...)
1473
 
    _see_also = ['status', 'ls']
1474
1152
    takes_options = ['show-ids']
1475
1153
 
1476
1154
    @display_command
1477
1155
    def run(self, show_ids=False):
1478
1156
        tree = WorkingTree.open_containing(u'.')[0]
1479
 
        tree.lock_read()
1480
 
        try:
1481
 
            old = tree.basis_tree()
1482
 
            old.lock_read()
1483
 
            try:
1484
 
                for path, ie in old.inventory.iter_entries():
1485
 
                    if not tree.has_id(ie.file_id):
1486
 
                        self.outf.write(path)
1487
 
                        if show_ids:
1488
 
                            self.outf.write(' ')
1489
 
                            self.outf.write(ie.file_id)
1490
 
                        self.outf.write('\n')
1491
 
            finally:
1492
 
                old.unlock()
1493
 
        finally:
1494
 
            tree.unlock()
 
1157
        old = tree.basis_tree()
 
1158
        for path, ie in old.inventory.iter_entries():
 
1159
            if not tree.has_id(ie.file_id):
 
1160
                self.outf.write(path)
 
1161
                if show_ids:
 
1162
                    self.outf.write(' ')
 
1163
                    self.outf.write(ie.file_id)
 
1164
                self.outf.write('\n')
1495
1165
 
1496
1166
 
1497
1167
class cmd_modified(Command):
1498
 
    """List files modified in working tree.
1499
 
    """
1500
 
 
 
1168
    """List files modified in working tree."""
1501
1169
    hidden = True
1502
 
    _see_also = ['status', 'ls']
1503
 
 
1504
1170
    @display_command
1505
1171
    def run(self):
 
1172
        from bzrlib.delta import compare_trees
 
1173
 
1506
1174
        tree = WorkingTree.open_containing(u'.')[0]
1507
 
        td = tree.changes_from(tree.basis_tree())
 
1175
        td = compare_trees(tree.basis_tree(), tree)
 
1176
 
1508
1177
        for path, id, kind, text_modified, meta_modified in td.modified:
1509
 
            self.outf.write(path + '\n')
 
1178
            self.outf.write(path)
 
1179
            self.outf.write('\n')
1510
1180
 
1511
1181
 
1512
1182
class cmd_added(Command):
1513
 
    """List files added in working tree.
1514
 
    """
1515
 
 
 
1183
    """List files added in working tree."""
1516
1184
    hidden = True
1517
 
    _see_also = ['status', 'ls']
1518
 
 
1519
1185
    @display_command
1520
1186
    def run(self):
1521
1187
        wt = WorkingTree.open_containing(u'.')[0]
1522
 
        wt.lock_read()
1523
 
        try:
1524
 
            basis = wt.basis_tree()
1525
 
            basis.lock_read()
1526
 
            try:
1527
 
                basis_inv = basis.inventory
1528
 
                inv = wt.inventory
1529
 
                for file_id in inv:
1530
 
                    if file_id in basis_inv:
1531
 
                        continue
1532
 
                    if inv.is_root(file_id) and len(basis_inv) == 0:
1533
 
                        continue
1534
 
                    path = inv.id2path(file_id)
1535
 
                    if not os.access(osutils.abspath(path), os.F_OK):
1536
 
                        continue
1537
 
                    self.outf.write(path + '\n')
1538
 
            finally:
1539
 
                basis.unlock()
1540
 
        finally:
1541
 
            wt.unlock()
 
1188
        basis_inv = wt.basis_tree().inventory
 
1189
        inv = wt.inventory
 
1190
        for file_id in inv:
 
1191
            if file_id in basis_inv:
 
1192
                continue
 
1193
            path = inv.id2path(file_id)
 
1194
            if not os.access(bzrlib.osutils.abspath(path), os.F_OK):
 
1195
                continue
 
1196
            self.outf.write(path)
 
1197
            self.outf.write('\n')
1542
1198
 
1543
1199
 
1544
1200
class cmd_root(Command):
1546
1202
 
1547
1203
    The root is the nearest enclosing directory with a .bzr control
1548
1204
    directory."""
1549
 
 
1550
1205
    takes_args = ['filename?']
1551
1206
    @display_command
1552
1207
    def run(self, filename=None):
1553
1208
        """Print the branch root."""
1554
1209
        tree = WorkingTree.open_containing(filename)[0]
1555
 
        self.outf.write(tree.basedir + '\n')
1556
 
 
1557
 
 
1558
 
def _parse_limit(limitstring):
1559
 
    try:
1560
 
        return int(limitstring)
1561
 
    except ValueError:
1562
 
        msg = "The limit argument must be an integer."
1563
 
        raise errors.BzrCommandError(msg)
 
1210
        self.outf.write(tree.basedir)
 
1211
        self.outf.write('\n')
1564
1212
 
1565
1213
 
1566
1214
class cmd_log(Command):
1585
1233
                            help='show from oldest to newest'),
1586
1234
                     'timezone', 
1587
1235
                     Option('verbose', 
1588
 
                             short_name='v',
1589
1236
                             help='show files changed in each revision'),
1590
1237
                     'show-ids', 'revision',
1591
1238
                     'log-format',
 
1239
                     'line', 'long', 
1592
1240
                     Option('message',
1593
 
                            short_name='m',
1594
1241
                            help='show revisions whose message matches this regexp',
1595
1242
                            type=str),
1596
 
                     Option('limit', 
1597
 
                            help='limit the output to the first N revisions',
1598
 
                            type=_parse_limit),
 
1243
                     'short',
1599
1244
                     ]
1600
1245
    encoding_type = 'replace'
1601
1246
 
1607
1252
            revision=None,
1608
1253
            log_format=None,
1609
1254
            message=None,
1610
 
            limit=None):
1611
 
        from bzrlib.log import show_log
 
1255
            long=False,
 
1256
            short=False,
 
1257
            line=False):
 
1258
        from bzrlib.log import log_formatter, show_log
1612
1259
        assert message is None or isinstance(message, basestring), \
1613
1260
            "invalid message argument %r" % message
1614
1261
        direction = (forward and 'forward') or 'reverse'
1618
1265
        if location:
1619
1266
            # find the file id to log:
1620
1267
 
1621
 
            tree, b, fp = bzrdir.BzrDir.open_containing_tree_or_branch(
1622
 
                location)
 
1268
            dir, fp = bzrdir.BzrDir.open_containing(location)
 
1269
            b = dir.open_branch()
1623
1270
            if fp != '':
1624
 
                if tree is None:
1625
 
                    tree = b.basis_tree()
1626
 
                file_id = tree.path2id(fp)
1627
 
                if file_id is None:
1628
 
                    raise errors.BzrCommandError(
1629
 
                        "Path does not have any revision history: %s" %
1630
 
                        location)
 
1271
                try:
 
1272
                    # might be a tree:
 
1273
                    inv = dir.open_workingtree().inventory
 
1274
                except (errors.NotBranchError, errors.NotLocalUrl):
 
1275
                    # either no tree, or is remote.
 
1276
                    inv = b.basis_tree().inventory
 
1277
                file_id = inv.path2id(fp)
1631
1278
        else:
1632
1279
            # local dir only
1633
1280
            # FIXME ? log the current subdir only RBC 20060203 
1634
 
            if revision is not None \
1635
 
                    and len(revision) > 0 and revision[0].get_branch():
1636
 
                location = revision[0].get_branch()
1637
 
            else:
1638
 
                location = '.'
1639
 
            dir, relpath = bzrdir.BzrDir.open_containing(location)
 
1281
            dir, relpath = bzrdir.BzrDir.open_containing('.')
1640
1282
            b = dir.open_branch()
1641
1283
 
1642
 
        b.lock_read()
1643
 
        try:
1644
 
            if revision is None:
1645
 
                rev1 = None
1646
 
                rev2 = None
1647
 
            elif len(revision) == 1:
1648
 
                rev1 = rev2 = revision[0].in_history(b)
1649
 
            elif len(revision) == 2:
1650
 
                if revision[1].get_branch() != revision[0].get_branch():
1651
 
                    # b is taken from revision[0].get_branch(), and
1652
 
                    # show_log will use its revision_history. Having
1653
 
                    # different branches will lead to weird behaviors.
1654
 
                    raise errors.BzrCommandError(
1655
 
                        "Log doesn't accept two revisions in different"
1656
 
                        " branches.")
1657
 
                rev1 = revision[0].in_history(b)
1658
 
                rev2 = revision[1].in_history(b)
1659
 
            else:
1660
 
                raise errors.BzrCommandError(
1661
 
                    'bzr log --revision takes one or two values.')
1662
 
 
1663
 
            if log_format is None:
1664
 
                log_format = log.log_formatter_registry.get_default(b)
1665
 
 
1666
 
            lf = log_format(show_ids=show_ids, to_file=self.outf,
1667
 
                            show_timezone=timezone)
1668
 
 
1669
 
            show_log(b,
1670
 
                     lf,
1671
 
                     file_id,
1672
 
                     verbose=verbose,
1673
 
                     direction=direction,
1674
 
                     start_revision=rev1,
1675
 
                     end_revision=rev2,
1676
 
                     search=message,
1677
 
                     limit=limit)
1678
 
        finally:
1679
 
            b.unlock()
 
1284
        if revision is None:
 
1285
            rev1 = None
 
1286
            rev2 = None
 
1287
        elif len(revision) == 1:
 
1288
            rev1 = rev2 = revision[0].in_history(b).revno
 
1289
        elif len(revision) == 2:
 
1290
            if revision[0].spec is None:
 
1291
                # missing begin-range means first revision
 
1292
                rev1 = 1
 
1293
            else:
 
1294
                rev1 = revision[0].in_history(b).revno
 
1295
 
 
1296
            if revision[1].spec is None:
 
1297
                # missing end-range means last known revision
 
1298
                rev2 = b.revno()
 
1299
            else:
 
1300
                rev2 = revision[1].in_history(b).revno
 
1301
        else:
 
1302
            raise BzrCommandError('bzr log --revision takes one or two values.')
 
1303
 
 
1304
        # By this point, the revision numbers are converted to the +ve
 
1305
        # form if they were supplied in the -ve form, so we can do
 
1306
        # this comparison in relative safety
 
1307
        if rev1 > rev2:
 
1308
            (rev2, rev1) = (rev1, rev2)
 
1309
 
 
1310
        if (log_format == None):
 
1311
            default = bzrlib.config.BranchConfig(b).log_format()
 
1312
            log_format = get_log_format(long=long, short=short, line=line, default=default)
 
1313
        lf = log_formatter(log_format,
 
1314
                           show_ids=show_ids,
 
1315
                           to_file=self.outf,
 
1316
                           show_timezone=timezone)
 
1317
 
 
1318
        show_log(b,
 
1319
                 lf,
 
1320
                 file_id,
 
1321
                 verbose=verbose,
 
1322
                 direction=direction,
 
1323
                 start_revision=rev1,
 
1324
                 end_revision=rev2,
 
1325
                 search=message)
1680
1326
 
1681
1327
 
1682
1328
def get_log_format(long=False, short=False, line=False, default='long'):
1693
1339
class cmd_touching_revisions(Command):
1694
1340
    """Return revision-ids which affected a particular file.
1695
1341
 
1696
 
    A more user-friendly interface is "bzr log FILE".
1697
 
    """
1698
 
 
 
1342
    A more user-friendly interface is "bzr log FILE"."""
1699
1343
    hidden = True
1700
1344
    takes_args = ["filename"]
1701
1345
 
1703
1347
    def run(self, filename):
1704
1348
        tree, relpath = WorkingTree.open_containing(filename)
1705
1349
        b = tree.branch
1706
 
        file_id = tree.path2id(relpath)
1707
 
        for revno, revision_id, what in log.find_touching_revisions(b, file_id):
 
1350
        inv = tree.read_working_inventory()
 
1351
        file_id = inv.path2id(relpath)
 
1352
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
1708
1353
            self.outf.write("%6d %s\n" % (revno, what))
1709
1354
 
1710
1355
 
1711
1356
class cmd_ls(Command):
1712
1357
    """List files in a tree.
1713
1358
    """
1714
 
 
1715
 
    _see_also = ['status', 'cat']
1716
 
    takes_args = ['path?']
1717
1359
    # TODO: Take a revision or remote path and list that tree instead.
 
1360
    hidden = True
1718
1361
    takes_options = ['verbose', 'revision',
1719
1362
                     Option('non-recursive',
1720
1363
                            help='don\'t recurse into sub-directories'),
1725
1368
                     Option('ignored', help='Print ignored files'),
1726
1369
 
1727
1370
                     Option('null', help='Null separate the files'),
1728
 
                     'kind', 'show-ids'
1729
1371
                    ]
1730
1372
    @display_command
1731
1373
    def run(self, revision=None, verbose=False, 
1732
1374
            non_recursive=False, from_root=False,
1733
1375
            unknown=False, versioned=False, ignored=False,
1734
 
            null=False, kind=None, show_ids=False, path=None):
1735
 
 
1736
 
        if kind and kind not in ('file', 'directory', 'symlink'):
1737
 
            raise errors.BzrCommandError('invalid kind specified')
 
1376
            null=False):
1738
1377
 
1739
1378
        if verbose and null:
1740
 
            raise errors.BzrCommandError('Cannot set both --verbose and --null')
 
1379
            raise BzrCommandError('Cannot set both --verbose and --null')
1741
1380
        all = not (unknown or versioned or ignored)
1742
1381
 
1743
1382
        selection = {'I':ignored, '?':unknown, 'V':versioned}
1744
1383
 
1745
 
        if path is None:
1746
 
            fs_path = '.'
1747
 
            prefix = ''
1748
 
        else:
1749
 
            if from_root:
1750
 
                raise errors.BzrCommandError('cannot specify both --from-root'
1751
 
                                             ' and PATH')
1752
 
            fs_path = path
1753
 
            prefix = path
1754
 
        tree, branch, relpath = bzrdir.BzrDir.open_containing_tree_or_branch(
1755
 
            fs_path)
 
1384
        tree, relpath = WorkingTree.open_containing(u'.')
1756
1385
        if from_root:
1757
1386
            relpath = u''
1758
1387
        elif relpath:
1759
1388
            relpath += '/'
1760
1389
        if revision is not None:
1761
 
            tree = branch.repository.revision_tree(
1762
 
                revision[0].in_history(branch).rev_id)
1763
 
        elif tree is None:
1764
 
            tree = branch.basis_tree()
 
1390
            tree = tree.branch.repository.revision_tree(
 
1391
                revision[0].in_history(tree.branch).rev_id)
1765
1392
 
1766
 
        tree.lock_read()
1767
 
        try:
1768
 
            for fp, fc, fkind, fid, entry in tree.list_files(include_root=False):
1769
 
                if fp.startswith(relpath):
1770
 
                    fp = osutils.pathjoin(prefix, fp[len(relpath):])
1771
 
                    if non_recursive and '/' in fp:
1772
 
                        continue
1773
 
                    if not all and not selection[fc]:
1774
 
                        continue
1775
 
                    if kind is not None and fkind != kind:
1776
 
                        continue
1777
 
                    if verbose:
1778
 
                        kindch = entry.kind_character()
1779
 
                        outstring = '%-8s %s%s' % (fc, fp, kindch)
1780
 
                        if show_ids and fid is not None:
1781
 
                            outstring = "%-50s %s" % (outstring, fid)
1782
 
                        self.outf.write(outstring + '\n')
1783
 
                    elif null:
1784
 
                        self.outf.write(fp + '\0')
1785
 
                        if show_ids:
1786
 
                            if fid is not None:
1787
 
                                self.outf.write(fid)
1788
 
                            self.outf.write('\0')
1789
 
                        self.outf.flush()
1790
 
                    else:
1791
 
                        if fid is not None:
1792
 
                            my_id = fid
1793
 
                        else:
1794
 
                            my_id = ''
1795
 
                        if show_ids:
1796
 
                            self.outf.write('%-50s %s\n' % (fp, my_id))
1797
 
                        else:
1798
 
                            self.outf.write(fp + '\n')
1799
 
        finally:
1800
 
            tree.unlock()
 
1393
        for fp, fc, kind, fid, entry in tree.list_files():
 
1394
            if fp.startswith(relpath):
 
1395
                fp = fp[len(relpath):]
 
1396
                if non_recursive and '/' in fp:
 
1397
                    continue
 
1398
                if not all and not selection[fc]:
 
1399
                    continue
 
1400
                if verbose:
 
1401
                    kindch = entry.kind_character()
 
1402
                    self.outf.write('%-8s %s%s\n' % (fc, fp, kindch))
 
1403
                elif null:
 
1404
                    self.outf.write(fp)
 
1405
                    self.outf.write('\0')
 
1406
                    self.outf.flush()
 
1407
                else:
 
1408
                    self.outf.write(fp)
 
1409
                    self.outf.write('\n')
1801
1410
 
1802
1411
 
1803
1412
class cmd_unknowns(Command):
1804
 
    """List unknown files.
1805
 
    """
1806
 
 
1807
 
    hidden = True
1808
 
    _see_also = ['ls']
1809
 
 
 
1413
    """List unknown files."""
1810
1414
    @display_command
1811
1415
    def run(self):
 
1416
        from bzrlib.osutils import quotefn
1812
1417
        for f in WorkingTree.open_containing(u'.')[0].unknowns():
1813
 
            self.outf.write(osutils.quotefn(f) + '\n')
 
1418
            self.outf.write(quotefn(f))
 
1419
            self.outf.write('\n')
1814
1420
 
1815
1421
 
1816
1422
class cmd_ignore(Command):
1817
 
    """Ignore specified files or patterns.
 
1423
    """Ignore a command or pattern.
1818
1424
 
1819
1425
    To remove patterns from the ignore list, edit the .bzrignore file.
1820
1426
 
1821
 
    Trailing slashes on patterns are ignored. 
1822
 
    If the pattern contains a slash or is a regular expression, it is compared 
1823
 
    to the whole path from the branch root.  Otherwise, it is compared to only
1824
 
    the last component of the path.  To match a file only in the root 
1825
 
    directory, prepend './'.
1826
 
 
1827
 
    Ignore patterns specifying absolute paths are not allowed.
1828
 
 
1829
 
    Ignore patterns may include globbing wildcards such as:
1830
 
      ? - Matches any single character except '/'
1831
 
      * - Matches 0 or more characters except '/'
1832
 
      /**/ - Matches 0 or more directories in a path
1833
 
      [a-z] - Matches a single character from within a group of characters
1834
 
 
1835
 
    Ignore patterns may also be Python regular expressions.  
1836
 
    Regular expression ignore patterns are identified by a 'RE:' prefix 
1837
 
    followed by the regular expression.  Regular expression ignore patterns
1838
 
    may not include named or numbered groups.
1839
 
 
1840
 
    Note: ignore patterns containing shell wildcards must be quoted from 
1841
 
    the shell on Unix.
 
1427
    If the pattern contains a slash, it is compared to the whole path
 
1428
    from the branch root.  Otherwise, it is compared to only the last
 
1429
    component of the path.  To match a file only in the root directory,
 
1430
    prepend './'.
 
1431
 
 
1432
    Ignore patterns are case-insensitive on case-insensitive systems.
 
1433
 
 
1434
    Note: wildcards must be quoted from the shell on Unix.
1842
1435
 
1843
1436
    examples:
1844
1437
        bzr ignore ./Makefile
1845
1438
        bzr ignore '*.class'
1846
 
        bzr ignore 'lib/**/*.o'
1847
 
        bzr ignore 'RE:lib/.*\.o'
1848
1439
    """
1849
 
 
1850
 
    _see_also = ['status', 'ignored']
1851
 
    takes_args = ['name_pattern*']
1852
 
    takes_options = [
1853
 
                     Option('old-default-rules',
1854
 
                            help='Out the ignore rules bzr < 0.9 always used.')
1855
 
                     ]
 
1440
    # TODO: Complain if the filename is absolute
 
1441
    takes_args = ['name_pattern']
1856
1442
    
1857
 
    def run(self, name_pattern_list=None, old_default_rules=None):
 
1443
    def run(self, name_pattern):
1858
1444
        from bzrlib.atomicfile import AtomicFile
1859
 
        if old_default_rules is not None:
1860
 
            # dump the rules and exit
1861
 
            for pattern in ignores.OLD_DEFAULTS:
1862
 
                print pattern
1863
 
            return
1864
 
        if not name_pattern_list:
1865
 
            raise errors.BzrCommandError("ignore requires at least one "
1866
 
                                  "NAME_PATTERN or --old-default-rules")
1867
 
        name_pattern_list = [globbing.normalize_pattern(p) 
1868
 
                             for p in name_pattern_list]
1869
 
        for name_pattern in name_pattern_list:
1870
 
            if (name_pattern[0] == '/' or 
1871
 
                (len(name_pattern) > 1 and name_pattern[1] == ':')):
1872
 
                raise errors.BzrCommandError(
1873
 
                    "NAME_PATTERN should not be an absolute path")
 
1445
        import os.path
 
1446
 
1874
1447
        tree, relpath = WorkingTree.open_containing(u'.')
1875
1448
        ifn = tree.abspath('.bzrignore')
 
1449
 
1876
1450
        if os.path.exists(ifn):
1877
1451
            f = open(ifn, 'rt')
1878
1452
            try:
1887
1461
 
1888
1462
        if igns and igns[-1] != '\n':
1889
1463
            igns += '\n'
1890
 
        for name_pattern in name_pattern_list:
1891
 
            igns += name_pattern + '\n'
 
1464
        igns += name_pattern + '\n'
1892
1465
 
1893
 
        f = AtomicFile(ifn, 'wb')
 
1466
        f = AtomicFile(ifn, 'wt')
1894
1467
        try:
1895
1468
            f.write(igns.encode('utf-8'))
1896
1469
            f.commit()
1897
1470
        finally:
1898
1471
            f.close()
1899
1472
 
1900
 
        if not tree.path2id('.bzrignore'):
 
1473
        inv = tree.inventory
 
1474
        if inv.path2id('.bzrignore'):
 
1475
            mutter('.bzrignore is already versioned')
 
1476
        else:
 
1477
            mutter('need to make new .bzrignore file versioned')
1901
1478
            tree.add(['.bzrignore'])
1902
1479
 
1903
1480
 
1904
1481
class cmd_ignored(Command):
1905
1482
    """List ignored files and the patterns that matched them.
1906
 
    """
1907
1483
 
1908
 
    _see_also = ['ignore']
 
1484
    See also: bzr ignore"""
1909
1485
    @display_command
1910
1486
    def run(self):
1911
1487
        tree = WorkingTree.open_containing(u'.')[0]
1912
 
        tree.lock_read()
1913
 
        try:
1914
 
            for path, file_class, kind, file_id, entry in tree.list_files():
1915
 
                if file_class != 'I':
1916
 
                    continue
1917
 
                ## XXX: Slightly inefficient since this was already calculated
1918
 
                pat = tree.is_ignored(path)
1919
 
                print '%-50s %s' % (path, pat)
1920
 
        finally:
1921
 
            tree.unlock()
 
1488
        for path, file_class, kind, file_id, entry in tree.list_files():
 
1489
            if file_class != 'I':
 
1490
                continue
 
1491
            ## XXX: Slightly inefficient since this was already calculated
 
1492
            pat = tree.is_ignored(path)
 
1493
            print '%-50s %s' % (path, pat)
1922
1494
 
1923
1495
 
1924
1496
class cmd_lookup_revision(Command):
1935
1507
        try:
1936
1508
            revno = int(revno)
1937
1509
        except ValueError:
1938
 
            raise errors.BzrCommandError("not a valid revision-number: %r" % revno)
 
1510
            raise BzrCommandError("not a valid revision-number: %r" % revno)
1939
1511
 
1940
1512
        print WorkingTree.open_containing(u'.')[0].branch.get_rev_id(revno)
1941
1513
 
1942
1514
 
1943
1515
class cmd_export(Command):
1944
 
    """Export current or past revision to a destination directory or archive.
 
1516
    """Export past revision to destination directory.
1945
1517
 
1946
1518
    If no revision is specified this exports the last committed revision.
1947
1519
 
1949
1521
    given, try to find the format with the extension. If no extension
1950
1522
    is found exports to a directory (equivalent to --format=dir).
1951
1523
 
1952
 
    If root is supplied, it will be used as the root directory inside
1953
 
    container formats (tar, zip, etc). If it is not supplied it will default
1954
 
    to the exported filename. The root option has no effect for 'dir' format.
1955
 
 
1956
 
    If branch is omitted then the branch containing the current working
1957
 
    directory will be used.
1958
 
 
1959
 
    Note: Export of tree with non-ASCII filenames to zip is not supported.
 
1524
    Root may be the top directory for tar, tgz and tbz2 formats. If none
 
1525
    is given, the top directory will be the root name of the file.
 
1526
 
 
1527
    Note: export of tree with non-ascii filenames to zip is not supported.
1960
1528
 
1961
1529
     Supported formats       Autodetected by extension
1962
1530
     -----------------       -------------------------
1966
1534
         tgz                      .tar.gz, .tgz
1967
1535
         zip                          .zip
1968
1536
    """
1969
 
    takes_args = ['dest', 'branch?']
 
1537
    takes_args = ['dest']
1970
1538
    takes_options = ['revision', 'format', 'root']
1971
 
    def run(self, dest, branch=None, revision=None, format=None, root=None):
 
1539
    def run(self, dest, revision=None, format=None, root=None):
 
1540
        import os.path
1972
1541
        from bzrlib.export import export
1973
 
 
1974
 
        if branch is None:
1975
 
            tree = WorkingTree.open_containing(u'.')[0]
1976
 
            b = tree.branch
1977
 
        else:
1978
 
            b = Branch.open(branch)
1979
 
            
 
1542
        tree = WorkingTree.open_containing(u'.')[0]
 
1543
        b = tree.branch
1980
1544
        if revision is None:
1981
1545
            # should be tree.last_revision  FIXME
1982
1546
            rev_id = b.last_revision()
1983
1547
        else:
1984
1548
            if len(revision) != 1:
1985
 
                raise errors.BzrCommandError('bzr export --revision takes exactly 1 argument')
 
1549
                raise BzrError('bzr export --revision takes exactly 1 argument')
1986
1550
            rev_id = revision[0].in_history(b).rev_id
1987
1551
        t = b.repository.revision_tree(rev_id)
1988
1552
        try:
1989
1553
            export(t, dest, format, root)
1990
1554
        except errors.NoSuchExportFormat, e:
1991
 
            raise errors.BzrCommandError('Unsupported export format: %s' % e.format)
 
1555
            raise BzrCommandError('Unsupported export format: %s' % e.format)
1992
1556
 
1993
1557
 
1994
1558
class cmd_cat(Command):
1995
 
    """Write the contents of a file as of a given revision to standard output.
1996
 
 
1997
 
    If no revision is nominated, the last revision is used.
1998
 
 
1999
 
    Note: Take care to redirect standard output when using this command on a
2000
 
    binary file. 
2001
 
    """
2002
 
 
2003
 
    _see_also = ['ls']
2004
 
    takes_options = ['revision', 'name-from-revision']
 
1559
    """Write a file's text from a previous revision."""
 
1560
 
 
1561
    takes_options = ['revision']
2005
1562
    takes_args = ['filename']
2006
 
    encoding_type = 'exact'
2007
1563
 
2008
1564
    @display_command
2009
 
    def run(self, filename, revision=None, name_from_revision=False):
 
1565
    def run(self, filename, revision=None):
2010
1566
        if revision is not None and len(revision) != 1:
2011
 
            raise errors.BzrCommandError("bzr cat --revision takes exactly"
2012
 
                                        " one number")
2013
 
 
 
1567
            raise BzrCommandError("bzr cat --revision takes exactly one number")
2014
1568
        tree = None
2015
1569
        try:
2016
 
            tree, b, relpath = \
2017
 
                    bzrdir.BzrDir.open_containing_tree_or_branch(filename)
2018
 
        except errors.NotBranchError:
 
1570
            tree, relpath = WorkingTree.open_containing(filename)
 
1571
            b = tree.branch
 
1572
        except NotBranchError:
2019
1573
            pass
2020
1574
 
2021
 
        if revision is not None and revision[0].get_branch() is not None:
2022
 
            b = Branch.open(revision[0].get_branch())
2023
1575
        if tree is None:
2024
 
            tree = b.basis_tree()
 
1576
            b, relpath = Branch.open_containing(filename)
2025
1577
        if revision is None:
2026
1578
            revision_id = b.last_revision()
2027
1579
        else:
2028
1580
            revision_id = revision[0].in_history(b).rev_id
2029
 
 
2030
 
        cur_file_id = tree.path2id(relpath)
2031
 
        rev_tree = b.repository.revision_tree(revision_id)
2032
 
        old_file_id = rev_tree.path2id(relpath)
2033
 
        
2034
 
        if name_from_revision:
2035
 
            if old_file_id is None:
2036
 
                raise errors.BzrCommandError("%r is not present in revision %s"
2037
 
                                                % (filename, revision_id))
2038
 
            else:
2039
 
                rev_tree.print_file(old_file_id)
2040
 
        elif cur_file_id is not None:
2041
 
            rev_tree.print_file(cur_file_id)
2042
 
        elif old_file_id is not None:
2043
 
            rev_tree.print_file(old_file_id)
2044
 
        else:
2045
 
            raise errors.BzrCommandError("%r is not present in revision %s" %
2046
 
                                         (filename, revision_id))
 
1581
        b.print_file(relpath, revision_id)
2047
1582
 
2048
1583
 
2049
1584
class cmd_local_time_offset(Command):
2051
1586
    hidden = True    
2052
1587
    @display_command
2053
1588
    def run(self):
2054
 
        print osutils.local_time_offset()
 
1589
        print bzrlib.osutils.local_time_offset()
2055
1590
 
2056
1591
 
2057
1592
 
2065
1600
    within it is committed.
2066
1601
 
2067
1602
    A selected-file commit may fail in some cases where the committed
2068
 
    tree would be invalid. Consider::
2069
 
 
2070
 
      bzr init foo
2071
 
      mkdir foo/bar
2072
 
      bzr add foo/bar
2073
 
      bzr commit foo -m "committing foo"
2074
 
      bzr mv foo/bar foo/baz
2075
 
      mkdir foo/bar
2076
 
      bzr add foo/bar
2077
 
      bzr commit foo/bar -m "committing bar but not baz"
2078
 
 
2079
 
    In the example above, the last commit will fail by design. This gives
2080
 
    the user the opportunity to decide whether they want to commit the
2081
 
    rename at the same time, separately first, or not at all. (As a general
2082
 
    rule, when in doubt, Bazaar has a policy of Doing the Safe Thing.)
2083
 
 
2084
 
    Note: A selected-file commit after a merge is not yet supported.
 
1603
    tree would be invalid, such as trying to commit a file in a
 
1604
    newly-added directory that is not itself committed.
2085
1605
    """
2086
1606
    # TODO: Run hooks on tree to-be-committed, and after commit.
2087
1607
 
2092
1612
 
2093
1613
    # XXX: verbose currently does nothing
2094
1614
 
2095
 
    _see_also = ['bugs', 'uncommit']
2096
1615
    takes_args = ['selected*']
2097
1616
    takes_options = ['message', 'verbose', 
2098
1617
                     Option('unchanged',
2099
1618
                            help='commit even if nothing has changed'),
2100
1619
                     Option('file', type=str, 
2101
 
                            short_name='F',
2102
1620
                            argname='msgfile',
2103
1621
                            help='file containing commit message'),
2104
1622
                     Option('strict',
2105
1623
                            help="refuse to commit if there are unknown "
2106
1624
                            "files in the working tree."),
2107
 
                     ListOption('fixes', type=str,
2108
 
                                help="mark a bug as being fixed by this "
2109
 
                                     "revision."),
2110
1625
                     Option('local',
2111
1626
                            help="perform a local only commit in a bound "
2112
1627
                                 "branch. Such commits are not pushed to "
2116
1631
                     ]
2117
1632
    aliases = ['ci', 'checkin']
2118
1633
 
2119
 
    def _get_bug_fix_properties(self, fixes, branch):
2120
 
        properties = []
2121
 
        # Configure the properties for bug fixing attributes.
2122
 
        for fixed_bug in fixes:
2123
 
            tokens = fixed_bug.split(':')
2124
 
            if len(tokens) != 2:
2125
 
                raise errors.BzrCommandError(
2126
 
                    "Invalid bug %s. Must be in the form of 'tag:id'. "
2127
 
                    "Commit refused." % fixed_bug)
2128
 
            tag, bug_id = tokens
2129
 
            try:
2130
 
                bug_url = bugtracker.get_bug_url(tag, branch, bug_id)
2131
 
            except errors.UnknownBugTrackerAbbreviation:
2132
 
                raise errors.BzrCommandError(
2133
 
                    'Unrecognized bug %s. Commit refused.' % fixed_bug)
2134
 
            except errors.MalformedBugIdentifier:
2135
 
                raise errors.BzrCommandError(
2136
 
                    "Invalid bug identifier for %s. Commit refused."
2137
 
                    % fixed_bug)
2138
 
            properties.append('%s fixed' % bug_url)
2139
 
        return '\n'.join(properties)
2140
 
 
2141
1634
    def run(self, message=None, file=None, verbose=True, selected_list=None,
2142
 
            unchanged=False, strict=False, local=False, fixes=None):
 
1635
            unchanged=False, strict=False, local=False):
2143
1636
        from bzrlib.commit import (NullCommitReporter, ReportCommitToLog)
2144
1637
        from bzrlib.errors import (PointlessCommit, ConflictsInTree,
2145
1638
                StrictCommitFailed)
2146
1639
        from bzrlib.msgeditor import edit_commit_message, \
2147
1640
                make_commit_message_template
 
1641
        from tempfile import TemporaryFile
2148
1642
 
2149
1643
        # TODO: Need a blackbox test for invoking the external editor; may be
2150
1644
        # slightly problematic to run this cross-platform.
2151
1645
 
2152
1646
        # TODO: do more checks that the commit will succeed before 
2153
1647
        # spending the user's valuable time typing a commit message.
2154
 
 
2155
 
        properties = {}
2156
 
 
 
1648
        #
 
1649
        # TODO: if the commit *does* happen to fail, then save the commit 
 
1650
        # message to a temporary file where it can be recovered
2157
1651
        tree, selected_list = tree_files(selected_list)
2158
1652
        if selected_list == ['']:
2159
1653
            # workaround - commit of root of tree should be exactly the same
2161
1655
            # selected-file merge commit is not done yet
2162
1656
            selected_list = []
2163
1657
 
2164
 
        bug_property = self._get_bug_fix_properties(fixes, tree.branch)
2165
 
        if bug_property:
2166
 
            properties['bugs'] = bug_property
2167
 
 
2168
1658
        if local and not tree.branch.get_bound_location():
2169
1659
            raise errors.LocalRequiresBoundBranch()
2170
 
 
2171
 
        def get_message(commit_obj):
2172
 
            """Callback to get commit message"""
2173
 
            my_message = message
2174
 
            if my_message is None and not file:
2175
 
                template = make_commit_message_template(tree, selected_list)
2176
 
                my_message = edit_commit_message(template)
2177
 
                if my_message is None:
2178
 
                    raise errors.BzrCommandError("please specify a commit"
2179
 
                        " message with either --message or --file")
2180
 
            elif my_message and file:
2181
 
                raise errors.BzrCommandError(
2182
 
                    "please specify either --message or --file")
2183
 
            if file:
2184
 
                my_message = codecs.open(file, 'rt', 
2185
 
                                         bzrlib.user_encoding).read()
2186
 
            if my_message == "":
2187
 
                raise errors.BzrCommandError("empty commit message specified")
2188
 
            return my_message
2189
 
 
 
1660
        if message is None and not file:
 
1661
            template = make_commit_message_template(tree, selected_list)
 
1662
            message = edit_commit_message(template)
 
1663
            if message is None:
 
1664
                raise BzrCommandError("please specify a commit message"
 
1665
                                      " with either --message or --file")
 
1666
        elif message and file:
 
1667
            raise BzrCommandError("please specify either --message or --file")
 
1668
        
 
1669
        if file:
 
1670
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
 
1671
 
 
1672
        if message == "":
 
1673
                raise BzrCommandError("empty commit message specified")
 
1674
        
2190
1675
        if verbose:
2191
1676
            reporter = ReportCommitToLog()
2192
1677
        else:
2193
1678
            reporter = NullCommitReporter()
2194
 
 
 
1679
        
2195
1680
        try:
2196
 
            tree.commit(message_callback=get_message,
2197
 
                        specific_files=selected_list,
 
1681
            tree.commit(message, specific_files=selected_list,
2198
1682
                        allow_pointless=unchanged, strict=strict, local=local,
2199
 
                        reporter=reporter, revprops=properties)
 
1683
                        reporter=reporter)
2200
1684
        except PointlessCommit:
2201
1685
            # FIXME: This should really happen before the file is read in;
2202
1686
            # perhaps prepare the commit; get the message; then actually commit
2203
 
            raise errors.BzrCommandError("no changes to commit."
2204
 
                              " use --unchanged to commit anyhow")
 
1687
            raise BzrCommandError("no changes to commit",
 
1688
                                  ["use --unchanged to commit anyhow"])
2205
1689
        except ConflictsInTree:
2206
 
            raise errors.BzrCommandError('Conflicts detected in working '
2207
 
                'tree.  Use "bzr conflicts" to list, "bzr resolve FILE" to'
2208
 
                ' resolve.')
 
1690
            raise BzrCommandError("Conflicts detected in working tree.  "
 
1691
                'Use "bzr conflicts" to list, "bzr resolve FILE" to resolve.')
2209
1692
        except StrictCommitFailed:
2210
 
            raise errors.BzrCommandError("Commit refused because there are"
2211
 
                              " unknown files in the working tree.")
 
1693
            raise BzrCommandError("Commit refused because there are unknown "
 
1694
                                  "files in the working tree.")
2212
1695
        except errors.BoundBranchOutOfDate, e:
2213
 
            raise errors.BzrCommandError(str(e) + "\n"
2214
 
            'To commit to master branch, run update and then commit.\n'
2215
 
            'You can also pass --local to commit to continue working '
2216
 
            'disconnected.')
 
1696
            raise BzrCommandError(str(e)
 
1697
                                  + ' Either unbind, update, or'
 
1698
                                    ' pass --local to commit.')
2217
1699
 
2218
1700
 
2219
1701
class cmd_check(Command):
2222
1704
    This command checks various invariants about the branch storage to
2223
1705
    detect data corruption or bzr bugs.
2224
1706
    """
2225
 
 
2226
 
    _see_also = ['reconcile']
2227
1707
    takes_args = ['branch?']
2228
1708
    takes_options = ['verbose']
2229
1709
 
2237
1717
        check(branch, verbose)
2238
1718
 
2239
1719
 
 
1720
class cmd_scan_cache(Command):
 
1721
    hidden = True
 
1722
    def run(self):
 
1723
        from bzrlib.hashcache import HashCache
 
1724
 
 
1725
        c = HashCache(u'.')
 
1726
        c.read()
 
1727
        c.scan()
 
1728
            
 
1729
        print '%6d stats' % c.stat_count
 
1730
        print '%6d in hashcache' % len(c._cache)
 
1731
        print '%6d files removed from cache' % c.removed_count
 
1732
        print '%6d hashes updated' % c.update_count
 
1733
        print '%6d files changed too recently to cache' % c.danger_count
 
1734
 
 
1735
        if c.needs_write:
 
1736
            c.write()
 
1737
 
 
1738
 
2240
1739
class cmd_upgrade(Command):
2241
1740
    """Upgrade branch storage to current format.
2242
1741
 
2244
1743
    this command. When the default format has changed you may also be warned
2245
1744
    during other operations to upgrade.
2246
1745
    """
2247
 
 
2248
 
    _see_also = ['check']
2249
1746
    takes_args = ['url?']
2250
1747
    takes_options = [
2251
 
                    RegistryOption('format',
2252
 
                        help='Upgrade to a specific format.  See "bzr help'
2253
 
                             ' formats" for details',
2254
 
                        registry=bzrdir.format_registry,
2255
 
                        converter=bzrdir.format_registry.make_bzrdir,
2256
 
                        value_switches=True, title='Branch format'),
 
1748
                     Option('format', 
 
1749
                            help='Upgrade to a specific format. Current formats'
 
1750
                                 ' are: default, knit, metaweave and weave.'
 
1751
                                 ' Default is knit; metaweave and weave are'
 
1752
                                 ' deprecated',
 
1753
                            type=get_format_type),
2257
1754
                    ]
2258
1755
 
 
1756
 
2259
1757
    def run(self, url='.', format=None):
2260
1758
        from bzrlib.upgrade import upgrade
2261
1759
        if format is None:
2262
 
            format = bzrdir.format_registry.make_bzrdir('default')
 
1760
            format = get_format_type('default')
2263
1761
        upgrade(url, format)
2264
1762
 
2265
1763
 
2266
1764
class cmd_whoami(Command):
2267
 
    """Show or set bzr user id.
2268
 
    
2269
 
    examples:
2270
 
        bzr whoami --email
2271
 
        bzr whoami 'Frank Chu <fchu@example.com>'
2272
 
    """
2273
 
    takes_options = [ Option('email',
2274
 
                             help='display email address only'),
2275
 
                      Option('branch',
2276
 
                             help='set identity for the current branch instead of '
2277
 
                                  'globally'),
2278
 
                    ]
2279
 
    takes_args = ['name?']
2280
 
    encoding_type = 'replace'
 
1765
    """Show bzr user id."""
 
1766
    takes_options = ['email']
2281
1767
    
2282
1768
    @display_command
2283
 
    def run(self, email=False, branch=False, name=None):
2284
 
        if name is None:
2285
 
            # use branch if we're inside one; otherwise global config
2286
 
            try:
2287
 
                c = Branch.open_containing('.')[0].get_config()
2288
 
            except errors.NotBranchError:
2289
 
                c = config.GlobalConfig()
2290
 
            if email:
2291
 
                self.outf.write(c.user_email() + '\n')
2292
 
            else:
2293
 
                self.outf.write(c.username() + '\n')
2294
 
            return
2295
 
 
2296
 
        # display a warning if an email address isn't included in the given name.
 
1769
    def run(self, email=False):
2297
1770
        try:
2298
 
            config.extract_email_address(name)
2299
 
        except errors.NoEmailInUsername, e:
2300
 
            warning('"%s" does not seem to contain an email address.  '
2301
 
                    'This is allowed, but not recommended.', name)
 
1771
            b = WorkingTree.open_containing(u'.')[0].branch
 
1772
            config = bzrlib.config.BranchConfig(b)
 
1773
        except NotBranchError:
 
1774
            config = bzrlib.config.GlobalConfig()
2302
1775
        
2303
 
        # use global config unless --branch given
2304
 
        if branch:
2305
 
            c = Branch.open_containing('.')[0].get_config()
 
1776
        if email:
 
1777
            print config.user_email()
2306
1778
        else:
2307
 
            c = config.GlobalConfig()
2308
 
        c.set_user_option('email', name)
 
1779
            print config.username()
2309
1780
 
2310
1781
 
2311
1782
class cmd_nick(Command):
2314
1785
    If unset, the tree root directory name is used as the nickname
2315
1786
    To print the current nickname, execute with no argument.  
2316
1787
    """
2317
 
 
2318
 
    _see_also = ['info']
2319
1788
    takes_args = ['nickname?']
2320
1789
    def run(self, nickname=None):
2321
1790
        branch = Branch.open_containing(u'.')[0]
2326
1795
 
2327
1796
    @display_command
2328
1797
    def printme(self, branch):
2329
 
        print branch.nick
 
1798
        print branch.nick 
2330
1799
 
2331
1800
 
2332
1801
class cmd_selftest(Command):
2333
1802
    """Run internal test suite.
2334
1803
    
2335
 
    If arguments are given, they are regular expressions that say which tests
2336
 
    should run.  Tests matching any expression are run, and other tests are
2337
 
    not run.
2338
 
 
2339
 
    Alternatively if --first is given, matching tests are run first and then
2340
 
    all other tests are run.  This is useful if you have been working in a
2341
 
    particular area, but want to make sure nothing else was broken.
2342
 
 
2343
 
    If --exclude is given, tests that match that regular expression are
2344
 
    excluded, regardless of whether they match --first or not.
2345
 
 
2346
 
    To help catch accidential dependencies between tests, the --randomize
2347
 
    option is useful. In most cases, the argument used is the word 'now'.
2348
 
    Note that the seed used for the random number generator is displayed
2349
 
    when this option is used. The seed can be explicitly passed as the
2350
 
    argument to this option if required. This enables reproduction of the
2351
 
    actual ordering used if and when an order sensitive problem is encountered.
2352
 
 
2353
 
    If --list-only is given, the tests that would be run are listed. This is
2354
 
    useful when combined with --first, --exclude and/or --randomize to
2355
 
    understand their impact. The test harness reports "Listed nn tests in ..."
2356
 
    instead of "Ran nn tests in ..." when list mode is enabled.
 
1804
    This creates temporary test directories in the working directory,
 
1805
    but not existing data is affected.  These directories are deleted
 
1806
    if the tests pass, or left behind to help in debugging if they
 
1807
    fail and --keep-output is specified.
 
1808
    
 
1809
    If arguments are given, they are regular expressions that say
 
1810
    which tests should run.
2357
1811
 
2358
1812
    If the global option '--no-plugins' is given, plugins are not loaded
2359
1813
    before running the selftests.  This has two effects: features provided or
2360
1814
    modified by plugins will not be tested, and tests provided by plugins will
2361
1815
    not be run.
2362
1816
 
2363
 
    examples::
 
1817
    examples:
2364
1818
        bzr selftest ignore
2365
 
            run only tests relating to 'ignore'
2366
1819
        bzr --no-plugins selftest -v
2367
 
            disable plugins and list tests as they're run
 
1820
    """
 
1821
    # TODO: --list should give a list of all available tests
2368
1822
 
2369
 
    For each test, that needs actual disk access, bzr create their own
2370
 
    subdirectory in the temporary testing directory (testXXXX.tmp).
2371
 
    By default the name of such subdirectory is based on the name of the test.
2372
 
    If option '--numbered-dirs' is given, bzr will use sequent numbers
2373
 
    of running tests to create such subdirectories. This is default behavior
2374
 
    on Windows because of path length limitation.
2375
 
    """
2376
1823
    # NB: this is used from the class without creating an instance, which is
2377
1824
    # why it does not have a self parameter.
2378
1825
    def get_transport_type(typestring):
2388
1835
            return FakeNFSServer
2389
1836
        msg = "No known transport type %s. Supported types are: sftp\n" %\
2390
1837
            (typestring)
2391
 
        raise errors.BzrCommandError(msg)
 
1838
        raise BzrCommandError(msg)
2392
1839
 
2393
1840
    hidden = True
2394
1841
    takes_args = ['testspecs*']
2395
1842
    takes_options = ['verbose',
2396
 
                     Option('one',
2397
 
                             help='stop when one test fails',
2398
 
                             short_name='1',
2399
 
                             ),
2400
 
                     Option('keep-output',
 
1843
                     Option('one', help='stop when one test fails'),
 
1844
                     Option('keep-output', 
2401
1845
                            help='keep output directories when tests fail'),
2402
 
                     Option('transport',
 
1846
                     Option('transport', 
2403
1847
                            help='Use a different transport by default '
2404
1848
                                 'throughout the test suite.',
2405
1849
                            type=get_transport_type),
2406
 
                     Option('benchmark', help='run the bzr benchmarks.'),
 
1850
                     Option('benchmark', help='run the bzr bencharks.'),
2407
1851
                     Option('lsprof-timed',
2408
1852
                            help='generate lsprof output for benchmarked'
2409
1853
                                 ' sections of code.'),
2410
 
                     Option('cache-dir', type=str,
2411
 
                            help='a directory to cache intermediate'
2412
 
                                 ' benchmark steps'),
2413
 
                     Option('clean-output',
2414
 
                            help='clean temporary tests directories'
2415
 
                                 ' without running tests'),
2416
 
                     Option('first',
2417
 
                            help='run all tests, but run specified tests first',
2418
 
                            short_name='f',
2419
 
                            ),
2420
 
                     Option('numbered-dirs',
2421
 
                            help='use numbered dirs for TestCaseInTempDir'),
2422
 
                     Option('list-only',
2423
 
                            help='list the tests instead of running them'),
2424
 
                     Option('randomize', type=str, argname="SEED",
2425
 
                            help='randomize the order of tests using the given'
2426
 
                                 ' seed or "now" for the current time'),
2427
 
                     Option('exclude', type=str, argname="PATTERN",
2428
 
                            short_name='x',
2429
 
                            help='exclude tests that match this regular'
2430
 
                                 ' expression'),
2431
1854
                     ]
2432
 
    encoding_type = 'replace'
2433
1855
 
2434
1856
    def run(self, testspecs_list=None, verbose=None, one=False,
2435
1857
            keep_output=False, transport=None, benchmark=None,
2436
 
            lsprof_timed=None, cache_dir=None, clean_output=False,
2437
 
            first=False, numbered_dirs=None, list_only=False,
2438
 
            randomize=None, exclude=None):
 
1858
            lsprof_timed=None):
2439
1859
        import bzrlib.ui
2440
1860
        from bzrlib.tests import selftest
2441
1861
        import bzrlib.benchmarks as benchmarks
2442
 
        from bzrlib.benchmarks import tree_creator
2443
 
 
2444
 
        if clean_output:
2445
 
            from bzrlib.tests import clean_selftest_output
2446
 
            clean_selftest_output()
2447
 
            return 0
2448
 
        if keep_output:
2449
 
            warning("notice: selftest --keep-output "
2450
 
                    "is no longer supported; "
2451
 
                    "test output is always removed")
2452
 
 
2453
 
        if numbered_dirs is None and sys.platform == 'win32':
2454
 
            numbered_dirs = True
2455
 
 
2456
 
        if cache_dir is not None:
2457
 
            tree_creator.TreeCreator.CACHE_ROOT = osutils.abspath(cache_dir)
2458
 
        print '%10s: %s' % ('bzr', osutils.realpath(sys.argv[0]))
 
1862
        # we don't want progress meters from the tests to go to the
 
1863
        # real output; and we don't want log messages cluttering up
 
1864
        # the real logs.
 
1865
        save_ui = bzrlib.ui.ui_factory
 
1866
        print '%10s: %s' % ('bzr', bzrlib.osutils.realpath(sys.argv[0]))
2459
1867
        print '%10s: %s' % ('bzrlib', bzrlib.__path__[0])
2460
1868
        print
2461
 
        if testspecs_list is not None:
2462
 
            pattern = '|'.join(testspecs_list)
2463
 
        else:
2464
 
            pattern = ".*"
2465
 
        if benchmark:
2466
 
            test_suite_factory = benchmarks.test_suite
2467
 
            if verbose is None:
2468
 
                verbose = True
2469
 
            # TODO: should possibly lock the history file...
2470
 
            benchfile = open(".perf_history", "at", buffering=1)
2471
 
        else:
2472
 
            test_suite_factory = None
2473
 
            if verbose is None:
2474
 
                verbose = False
2475
 
            benchfile = None
 
1869
        bzrlib.trace.info('running tests...')
2476
1870
        try:
 
1871
            bzrlib.ui.ui_factory = bzrlib.ui.SilentUIFactory()
 
1872
            if testspecs_list is not None:
 
1873
                pattern = '|'.join(testspecs_list)
 
1874
            else:
 
1875
                pattern = ".*"
 
1876
            if benchmark:
 
1877
                test_suite_factory = benchmarks.test_suite
 
1878
                if verbose is None:
 
1879
                    verbose = True
 
1880
            else:
 
1881
                test_suite_factory = None
 
1882
                if verbose is None:
 
1883
                    verbose = False
2477
1884
            result = selftest(verbose=verbose, 
2478
1885
                              pattern=pattern,
2479
1886
                              stop_on_failure=one, 
 
1887
                              keep_output=keep_output,
2480
1888
                              transport=transport,
2481
1889
                              test_suite_factory=test_suite_factory,
2482
 
                              lsprof_timed=lsprof_timed,
2483
 
                              bench_history=benchfile,
2484
 
                              matching_tests_first=first,
2485
 
                              numbered_dirs=numbered_dirs,
2486
 
                              list_only=list_only,
2487
 
                              random_seed=randomize,
2488
 
                              exclude_pattern=exclude
2489
 
                              )
 
1890
                              lsprof_timed=lsprof_timed)
 
1891
            if result:
 
1892
                bzrlib.trace.info('tests passed')
 
1893
            else:
 
1894
                bzrlib.trace.info('tests failed')
 
1895
            return int(not result)
2490
1896
        finally:
2491
 
            if benchfile is not None:
2492
 
                benchfile.close()
2493
 
        if result:
2494
 
            info('tests passed')
2495
 
        else:
2496
 
            info('tests failed')
2497
 
        return int(not result)
 
1897
            bzrlib.ui.ui_factory = save_ui
 
1898
 
 
1899
 
 
1900
def _get_bzr_branch():
 
1901
    """If bzr is run from a branch, return Branch or None"""
 
1902
    import bzrlib.errors
 
1903
    from bzrlib.branch import Branch
 
1904
    from bzrlib.osutils import abspath
 
1905
    from os.path import dirname
 
1906
    
 
1907
    try:
 
1908
        branch = Branch.open(dirname(abspath(dirname(__file__))))
 
1909
        return branch
 
1910
    except bzrlib.errors.BzrError:
 
1911
        return None
 
1912
    
 
1913
 
 
1914
def show_version():
 
1915
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
 
1916
    # is bzrlib itself in a branch?
 
1917
    branch = _get_bzr_branch()
 
1918
    if branch:
 
1919
        rh = branch.revision_history()
 
1920
        revno = len(rh)
 
1921
        print "  bzr checkout, revision %d" % (revno,)
 
1922
        print "  nick: %s" % (branch.nick,)
 
1923
        if rh:
 
1924
            print "  revid: %s" % (rh[-1],)
 
1925
    print "Using python interpreter:", sys.executable
 
1926
    import site
 
1927
    print "Using python standard library:", os.path.dirname(site.__file__)
 
1928
    print "Using bzrlib:",
 
1929
    if len(bzrlib.__path__) > 1:
 
1930
        # print repr, which is a good enough way of making it clear it's
 
1931
        # more than one element (eg ['/foo/bar', '/foo/bzr'])
 
1932
        print repr(bzrlib.__path__)
 
1933
    else:
 
1934
        print bzrlib.__path__[0]
 
1935
 
 
1936
    print
 
1937
    print bzrlib.__copyright__
 
1938
    print "http://bazaar-vcs.org/"
 
1939
    print
 
1940
    print "bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and"
 
1941
    print "you may use, modify and redistribute it under the terms of the GNU"
 
1942
    print "General Public License version 2 or later."
2498
1943
 
2499
1944
 
2500
1945
class cmd_version(Command):
2501
1946
    """Show version of bzr."""
2502
 
 
2503
1947
    @display_command
2504
1948
    def run(self):
2505
 
        from bzrlib.version import show_version
2506
1949
        show_version()
2507
1950
 
2508
 
 
2509
1951
class cmd_rocks(Command):
2510
1952
    """Statement of optimism."""
2511
 
 
2512
1953
    hidden = True
2513
 
 
2514
1954
    @display_command
2515
1955
    def run(self):
2516
 
        print "It sure does!"
 
1956
        print "it sure does!"
2517
1957
 
2518
1958
 
2519
1959
class cmd_find_merge_base(Command):
2520
 
    """Find and print a base revision for merging two branches."""
 
1960
    """Find and print a base revision for merging two branches.
 
1961
    """
2521
1962
    # TODO: Options to specify revisions on either side, as if
2522
1963
    #       merging only part of the history.
2523
1964
    takes_args = ['branch', 'other']
2525
1966
    
2526
1967
    @display_command
2527
1968
    def run(self, branch, other):
2528
 
        from bzrlib.revision import ensure_null, MultipleRevisionSources
 
1969
        from bzrlib.revision import common_ancestor, MultipleRevisionSources
2529
1970
        
2530
1971
        branch1 = Branch.open_containing(branch)[0]
2531
1972
        branch2 = Branch.open_containing(other)[0]
2532
1973
 
2533
 
        last1 = ensure_null(branch1.last_revision())
2534
 
        last2 = ensure_null(branch2.last_revision())
2535
 
 
2536
 
        graph = branch1.repository.get_graph(branch2.repository)
2537
 
        base_rev_id = graph.find_unique_lca(last1, last2)
 
1974
        history_1 = branch1.revision_history()
 
1975
        history_2 = branch2.revision_history()
 
1976
 
 
1977
        last1 = branch1.last_revision()
 
1978
        last2 = branch2.last_revision()
 
1979
 
 
1980
        source = MultipleRevisionSources(branch1.repository, 
 
1981
                                         branch2.repository)
 
1982
        
 
1983
        base_rev_id = common_ancestor(last1, last2, source)
2538
1984
 
2539
1985
        print 'merge base is revision %s' % base_rev_id
 
1986
        
 
1987
        return
 
1988
 
 
1989
        if base_revno is None:
 
1990
            raise bzrlib.errors.UnrelatedBranches()
 
1991
 
 
1992
        print ' r%-6d in %s' % (base_revno, branch)
 
1993
 
 
1994
        other_revno = branch2.revision_id_to_revno(base_revid)
 
1995
        
 
1996
        print ' r%-6d in %s' % (other_revno, other)
 
1997
 
2540
1998
 
2541
1999
 
2542
2000
class cmd_merge(Command):
2543
2001
    """Perform a three-way merge.
2544
2002
    
2545
 
    The branch is the branch you will merge from.  By default, it will merge
2546
 
    the latest revision.  If you specify a revision, that revision will be
2547
 
    merged.  If you specify two revisions, the first will be used as a BASE,
2548
 
    and the second one as OTHER.  Revision numbers are always relative to the
2549
 
    specified branch.
 
2003
    The branch is the branch you will merge from.  By default, it will
 
2004
    merge the latest revision.  If you specify a revision, that
 
2005
    revision will be merged.  If you specify two revisions, the first
 
2006
    will be used as a BASE, and the second one as OTHER.  Revision
 
2007
    numbers are always relative to the specified branch.
2550
2008
 
2551
2009
    By default, bzr will try to merge in all new work from the other
2552
2010
    branch, automatically determining an appropriate base.  If this
2561
2019
 
2562
2020
    If there is no default branch set, the first merge will set it. After
2563
2021
    that, you can omit the branch to use the default.  To change the
2564
 
    default, use --remember. The value will only be saved if the remote
2565
 
    location can be accessed.
2566
 
 
2567
 
    The results of the merge are placed into the destination working
2568
 
    directory, where they can be reviewed (with bzr diff), tested, and then
2569
 
    committed to record the result of the merge.
 
2022
    default, use --remember.
2570
2023
 
2571
2024
    Examples:
2572
2025
 
2573
 
    To merge the latest revision from bzr.dev:
2574
 
        bzr merge ../bzr.dev
 
2026
    To merge the latest revision from bzr.dev
 
2027
    bzr merge ../bzr.dev
2575
2028
 
2576
 
    To merge changes up to and including revision 82 from bzr.dev:
2577
 
        bzr merge -r 82 ../bzr.dev
 
2029
    To merge changes up to and including revision 82 from bzr.dev
 
2030
    bzr merge -r 82 ../bzr.dev
2578
2031
 
2579
2032
    To merge the changes introduced by 82, without previous changes:
2580
 
        bzr merge -r 81..82 ../bzr.dev
 
2033
    bzr merge -r 81..82 ../bzr.dev
2581
2034
    
2582
2035
    merge refuses to run if there are any uncommitted changes, unless
2583
2036
    --force is given.
 
2037
 
 
2038
    The following merge types are available:
2584
2039
    """
2585
 
 
2586
 
    _see_also = ['update', 'remerge', 'status-flags']
2587
2040
    takes_args = ['branch?']
2588
2041
    takes_options = ['revision', 'force', 'merge-type', 'reprocess', 'remember',
2589
 
        Option('show-base', help="Show base revision text in "
2590
 
               "conflicts"),
2591
 
        Option('uncommitted', help='Apply uncommitted changes'
2592
 
               ' from a working copy, instead of branch changes'),
2593
 
        Option('pull', help='If the destination is already'
2594
 
                ' completely merged into the source, pull from the'
2595
 
                ' source rather than merging. When this happens,'
2596
 
                ' you do not need to commit the result.'),
2597
 
        Option('directory',
2598
 
            help='Branch to merge into, '
2599
 
                 'rather than the one containing the working directory',
2600
 
            short_name='d',
2601
 
            type=unicode,
2602
 
            ),
2603
 
    ]
 
2042
                     Option('show-base', help="Show base revision text in "
 
2043
                            "conflicts")]
 
2044
 
 
2045
    def help(self):
 
2046
        from merge import merge_type_help
 
2047
        from inspect import getdoc
 
2048
        return getdoc(self) + '\n' + merge_type_help() 
2604
2049
 
2605
2050
    def run(self, branch=None, revision=None, force=False, merge_type=None,
2606
 
            show_base=False, reprocess=False, remember=False,
2607
 
            uncommitted=False, pull=False,
2608
 
            directory=None,
2609
 
            ):
2610
 
        from bzrlib.tag import _merge_tags_if_possible
2611
 
        other_revision_id = None
 
2051
            show_base=False, reprocess=False, remember=False):
2612
2052
        if merge_type is None:
2613
 
            merge_type = _mod_merge.Merge3Merger
2614
 
 
2615
 
        if directory is None: directory = u'.'
2616
 
        # XXX: jam 20070225 WorkingTree should be locked before you extract its
2617
 
        #      inventory. Because merge is a mutating operation, it really
2618
 
        #      should be a lock_write() for the whole cmd_merge operation.
2619
 
        #      However, cmd_merge open's its own tree in _merge_helper, which
2620
 
        #      means if we lock here, the later lock_write() will always block.
2621
 
        #      Either the merge helper code should be updated to take a tree,
2622
 
        #      (What about tree.merge_from_branch?)
2623
 
        tree = WorkingTree.open_containing(directory)[0]
2624
 
        change_reporter = delta._ChangeReporter(
2625
 
            unversioned_filter=tree.is_ignored)
2626
 
 
2627
 
        if branch is not None:
2628
 
            try:
2629
 
                mergeable = bundle.read_mergeable_from_url(
2630
 
                    branch)
2631
 
            except errors.NotABundle:
2632
 
                pass # Continue on considering this url a Branch
2633
 
            else:
2634
 
                if revision is not None:
2635
 
                    raise errors.BzrCommandError(
2636
 
                        'Cannot use -r with merge directives or bundles')
2637
 
                other_revision_id = mergeable.install_revisions(
2638
 
                    tree.branch.repository)
2639
 
                revision = [RevisionSpec.from_string(
2640
 
                    'revid:' + other_revision_id)]
2641
 
 
2642
 
        if revision is None \
2643
 
                or len(revision) < 1 or revision[0].needs_branch():
2644
 
            branch = self._get_remembered_parent(tree, branch, 'Merging from')
 
2053
            merge_type = Merge3Merger
 
2054
 
 
2055
        tree = WorkingTree.open_containing(u'.')[0]
 
2056
 
 
2057
        try:
 
2058
            if branch is not None:
 
2059
                reader = BundleReader(file(branch, 'rb'))
 
2060
            else:
 
2061
                reader = None
 
2062
        except IOError, e:
 
2063
            if e.errno not in (errno.ENOENT, errno.EISDIR):
 
2064
                raise
 
2065
            reader = None
 
2066
        except BadBundle:
 
2067
            reader = None
 
2068
        if reader is not None:
 
2069
            conflicts = merge_bundle(reader, tree, not force, merge_type,
 
2070
                                        reprocess, show_base)
 
2071
            if conflicts == 0:
 
2072
                return 0
 
2073
            else:
 
2074
                return 1
 
2075
 
 
2076
        branch = self._get_remembered_parent(tree, branch, 'Merging from')
2645
2077
 
2646
2078
        if revision is None or len(revision) < 1:
2647
 
            if uncommitted:
2648
 
                base = [branch, -1]
2649
 
                other = [branch, None]
2650
 
            else:
2651
 
                base = [None, None]
2652
 
                other = [branch, -1]
 
2079
            base = [None, None]
 
2080
            other = [branch, -1]
2653
2081
            other_branch, path = Branch.open_containing(branch)
2654
2082
        else:
2655
 
            if uncommitted:
2656
 
                raise errors.BzrCommandError('Cannot use --uncommitted and'
2657
 
                                             ' --revision at the same time.')
2658
 
            branch = revision[0].get_branch() or branch
2659
2083
            if len(revision) == 1:
2660
2084
                base = [None, None]
2661
 
                if other_revision_id is not None:
2662
 
                    other_branch = None
2663
 
                    path = ""
2664
 
                    other = None
2665
 
                else:
2666
 
                    other_branch, path = Branch.open_containing(branch)
2667
 
                    revno = revision[0].in_history(other_branch).revno
2668
 
                    other = [branch, revno]
 
2085
                other_branch, path = Branch.open_containing(branch)
 
2086
                revno = revision[0].in_history(other_branch).revno
 
2087
                other = [branch, revno]
2669
2088
            else:
2670
2089
                assert len(revision) == 2
2671
2090
                if None in revision:
2672
 
                    raise errors.BzrCommandError(
2673
 
                        "Merge doesn't permit empty revision specifier.")
2674
 
                base_branch, path = Branch.open_containing(branch)
2675
 
                branch1 = revision[1].get_branch() or branch
2676
 
                other_branch, path1 = Branch.open_containing(branch1)
2677
 
                if revision[0].get_branch() is not None:
2678
 
                    # then path was obtained from it, and is None.
2679
 
                    path = path1
2680
 
 
2681
 
                base = [branch, revision[0].in_history(base_branch).revno]
2682
 
                other = [branch1, revision[1].in_history(other_branch).revno]
2683
 
 
2684
 
        if ((tree.branch.get_parent() is None or remember) and
2685
 
            other_branch is not None):
 
2091
                    raise BzrCommandError(
 
2092
                        "Merge doesn't permit that revision specifier.")
 
2093
                other_branch, path = Branch.open_containing(branch)
 
2094
 
 
2095
                base = [branch, revision[0].in_history(other_branch).revno]
 
2096
                other = [branch, revision[1].in_history(other_branch).revno]
 
2097
 
 
2098
        if tree.branch.get_parent() is None or remember:
2686
2099
            tree.branch.set_parent(other_branch.base)
2687
2100
 
2688
 
        # pull tags now... it's a bit inconsistent to do it ahead of copying
2689
 
        # the history but that's done inside the merge code
2690
 
        if other_branch is not None:
2691
 
            _merge_tags_if_possible(other_branch, tree.branch)
2692
 
 
2693
2101
        if path != "":
2694
2102
            interesting_files = [path]
2695
2103
        else:
2696
2104
            interesting_files = None
2697
 
        pb = ui.ui_factory.nested_progress_bar()
 
2105
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
2698
2106
        try:
2699
2107
            try:
2700
 
                conflict_count = _merge_helper(
2701
 
                    other, base, other_rev_id=other_revision_id,
2702
 
                    check_clean=(not force),
2703
 
                    merge_type=merge_type,
2704
 
                    reprocess=reprocess,
2705
 
                    show_base=show_base,
2706
 
                    pull=pull,
2707
 
                    this_dir=directory,
2708
 
                    pb=pb, file_list=interesting_files,
2709
 
                    change_reporter=change_reporter)
 
2108
                conflict_count = merge(other, base, check_clean=(not force),
 
2109
                                       merge_type=merge_type,
 
2110
                                       reprocess=reprocess,
 
2111
                                       show_base=show_base,
 
2112
                                       pb=pb, file_list=interesting_files)
2710
2113
            finally:
2711
2114
                pb.finished()
2712
2115
            if conflict_count != 0:
2713
2116
                return 1
2714
2117
            else:
2715
2118
                return 0
2716
 
        except errors.AmbiguousBase, e:
 
2119
        except bzrlib.errors.AmbiguousBase, e:
2717
2120
            m = ("sorry, bzr can't determine the right merge base yet\n"
2718
2121
                 "candidates are:\n  "
2719
2122
                 + "\n  ".join(e.bases)
2733
2136
        stored_location = tree.branch.get_parent()
2734
2137
        mutter("%s", stored_location)
2735
2138
        if stored_location is None:
2736
 
            raise errors.BzrCommandError("No location specified or remembered")
 
2139
            raise BzrCommandError("No location specified or remembered")
2737
2140
        display_url = urlutils.unescape_for_display(stored_location, self.outf.encoding)
2738
2141
        self.outf.write("%s remembered location %s\n" % (verb_string, display_url))
2739
2142
        return stored_location
2751
2154
    pending merge, and it lets you specify particular files.
2752
2155
 
2753
2156
    Examples:
2754
 
 
2755
2157
    $ bzr remerge --show-base
2756
2158
        Re-do the merge of all conflicted files, and show the base text in
2757
2159
        conflict regions, in addition to the usual THIS and OTHER texts.
2759
2161
    $ bzr remerge --merge-type weave --reprocess foobar
2760
2162
        Re-do the merge of "foobar", using the weave merge algorithm, with
2761
2163
        additional processing to reduce the size of conflict regions.
2762
 
    """
 
2164
    
 
2165
    The following merge types are available:"""
2763
2166
    takes_args = ['file*']
2764
2167
    takes_options = ['merge-type', 'reprocess',
2765
2168
                     Option('show-base', help="Show base revision text in "
2766
2169
                            "conflicts")]
2767
2170
 
 
2171
    def help(self):
 
2172
        from merge import merge_type_help
 
2173
        from inspect import getdoc
 
2174
        return getdoc(self) + '\n' + merge_type_help() 
 
2175
 
2768
2176
    def run(self, file_list=None, merge_type=None, show_base=False,
2769
2177
            reprocess=False):
 
2178
        from bzrlib.merge import merge_inner, transform_tree
2770
2179
        if merge_type is None:
2771
 
            merge_type = _mod_merge.Merge3Merger
 
2180
            merge_type = Merge3Merger
2772
2181
        tree, file_list = tree_files(file_list)
2773
2182
        tree.lock_write()
2774
2183
        try:
2775
 
            parents = tree.get_parent_ids()
2776
 
            if len(parents) != 2:
2777
 
                raise errors.BzrCommandError("Sorry, remerge only works after normal"
2778
 
                                             " merges.  Not cherrypicking or"
2779
 
                                             " multi-merges.")
 
2184
            pending_merges = tree.pending_merges() 
 
2185
            if len(pending_merges) != 1:
 
2186
                raise BzrCommandError("Sorry, remerge only works after normal"
 
2187
                                      + " merges.  Not cherrypicking or"
 
2188
                                      + "multi-merges.")
2780
2189
            repository = tree.branch.repository
2781
 
            graph = repository.get_graph()
2782
 
            base_revision = graph.find_unique_lca(parents[0], parents[1])
 
2190
            base_revision = common_ancestor(tree.branch.last_revision(), 
 
2191
                                            pending_merges[0], repository)
2783
2192
            base_tree = repository.revision_tree(base_revision)
2784
 
            other_tree = repository.revision_tree(parents[1])
 
2193
            other_tree = repository.revision_tree(pending_merges[0])
2785
2194
            interesting_ids = None
2786
 
            new_conflicts = []
2787
 
            conflicts = tree.conflicts()
2788
2195
            if file_list is not None:
2789
2196
                interesting_ids = set()
2790
2197
                for filename in file_list:
2791
2198
                    file_id = tree.path2id(filename)
2792
2199
                    if file_id is None:
2793
 
                        raise errors.NotVersionedError(filename)
 
2200
                        raise NotVersionedError(filename)
2794
2201
                    interesting_ids.add(file_id)
2795
2202
                    if tree.kind(file_id) != "directory":
2796
2203
                        continue
2797
2204
                    
2798
2205
                    for name, ie in tree.inventory.iter_entries(file_id):
2799
2206
                        interesting_ids.add(ie.file_id)
2800
 
                new_conflicts = conflicts.select_conflicts(tree, file_list)[0]
 
2207
            transform_tree(tree, tree.basis_tree(), interesting_ids)
 
2208
            if file_list is None:
 
2209
                restore_files = list(tree.iter_conflicts())
2801
2210
            else:
2802
 
                # Remerge only supports resolving contents conflicts
2803
 
                allowed_conflicts = ('text conflict', 'contents conflict')
2804
 
                restore_files = [c.path for c in conflicts
2805
 
                                 if c.typestring in allowed_conflicts]
2806
 
            _mod_merge.transform_tree(tree, tree.basis_tree(), interesting_ids)
2807
 
            tree.set_conflicts(ConflictList(new_conflicts))
2808
 
            if file_list is not None:
2809
2211
                restore_files = file_list
2810
2212
            for filename in restore_files:
2811
2213
                try:
2812
2214
                    restore(tree.abspath(filename))
2813
 
                except errors.NotConflicted:
 
2215
                except NotConflicted:
2814
2216
                    pass
2815
 
            conflicts = _mod_merge.merge_inner(
2816
 
                                      tree.branch, other_tree, base_tree,
2817
 
                                      this_tree=tree,
2818
 
                                      interesting_ids=interesting_ids,
2819
 
                                      other_rev_id=parents[1],
2820
 
                                      merge_type=merge_type,
2821
 
                                      show_base=show_base,
2822
 
                                      reprocess=reprocess)
 
2217
            conflicts =  merge_inner(tree.branch, other_tree, base_tree,
 
2218
                                     this_tree=tree,
 
2219
                                     interesting_ids = interesting_ids, 
 
2220
                                     other_rev_id=pending_merges[0], 
 
2221
                                     merge_type=merge_type, 
 
2222
                                     show_base=show_base,
 
2223
                                     reprocess=reprocess)
2823
2224
        finally:
2824
2225
            tree.unlock()
2825
2226
        if conflicts > 0:
2827
2228
        else:
2828
2229
            return 0
2829
2230
 
2830
 
 
2831
2231
class cmd_revert(Command):
2832
 
    """Revert files to a previous revision.
2833
 
 
2834
 
    Giving a list of files will revert only those files.  Otherwise, all files
2835
 
    will be reverted.  If the revision is not specified with '--revision', the
2836
 
    last committed revision is used.
2837
 
 
2838
 
    To remove only some changes, without reverting to a prior version, use
2839
 
    merge instead.  For example, "merge . --r-2..-3" will remove the changes
2840
 
    introduced by -2, without affecting the changes introduced by -1.  Or
2841
 
    to remove certain changes on a hunk-by-hunk basis, see the Shelf plugin.
2842
 
    
2843
 
    By default, any files that have been manually changed will be backed up
2844
 
    first.  (Files changed only by merge are not backed up.)  Backup files have
2845
 
    '.~#~' appended to their name, where # is a number.
2846
 
 
2847
 
    When you provide files, you can use their current pathname or the pathname
2848
 
    from the target revision.  So you can use revert to "undelete" a file by
2849
 
    name.  If you name a directory, all the contents of that directory will be
2850
 
    reverted.
 
2232
    """Reverse all changes since the last commit.
 
2233
 
 
2234
    Only versioned files are affected.  Specify filenames to revert only 
 
2235
    those files.  By default, any files that are changed will be backed up
 
2236
    first.  Backup files have a '~' appended to their name.
2851
2237
    """
2852
 
 
2853
 
    _see_also = ['cat', 'export']
2854
2238
    takes_options = ['revision', 'no-backup']
2855
2239
    takes_args = ['file*']
 
2240
    aliases = ['merge-revert']
2856
2241
 
2857
2242
    def run(self, revision=None, no_backup=False, file_list=None):
 
2243
        from bzrlib.commands import parse_spec
2858
2244
        if file_list is not None:
2859
2245
            if len(file_list) == 0:
2860
 
                raise errors.BzrCommandError("No files specified")
 
2246
                raise BzrCommandError("No files specified")
2861
2247
        else:
2862
2248
            file_list = []
2863
2249
        
2866
2252
            # FIXME should be tree.last_revision
2867
2253
            rev_id = tree.last_revision()
2868
2254
        elif len(revision) != 1:
2869
 
            raise errors.BzrCommandError('bzr revert --revision takes exactly 1 argument')
 
2255
            raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
2870
2256
        else:
2871
2257
            rev_id = revision[0].in_history(tree.branch).rev_id
2872
 
        pb = ui.ui_factory.nested_progress_bar()
 
2258
        pb = bzrlib.ui.ui_factory.nested_progress_bar()
2873
2259
        try:
2874
2260
            tree.revert(file_list, 
2875
2261
                        tree.branch.repository.revision_tree(rev_id),
2876
 
                        not no_backup, pb, report_changes=True)
 
2262
                        not no_backup, pb)
2877
2263
        finally:
2878
2264
            pb.finished()
2879
2265
 
2880
2266
 
2881
2267
class cmd_assert_fail(Command):
2882
2268
    """Test reporting of assertion failures"""
2883
 
    # intended just for use in testing
2884
 
 
2885
2269
    hidden = True
2886
 
 
2887
2270
    def run(self):
2888
 
        raise AssertionError("always fails")
 
2271
        assert False, "always fails"
2889
2272
 
2890
2273
 
2891
2274
class cmd_help(Command):
2892
2275
    """Show help on a command or other topic.
2893
 
    """
2894
2276
 
2895
 
    _see_also = ['topics']
 
2277
    For a list of all available commands, say 'bzr help commands'."""
2896
2278
    takes_options = [Option('long', 'show help on all commands')]
2897
2279
    takes_args = ['topic?']
2898
2280
    aliases = ['?', '--help', '-?', '-h']
2899
2281
    
2900
2282
    @display_command
2901
2283
    def run(self, topic=None, long=False):
2902
 
        import bzrlib.help
 
2284
        import help
2903
2285
        if topic is None and long:
2904
2286
            topic = "commands"
2905
 
        bzrlib.help.help(topic)
 
2287
        help.help(topic)
2906
2288
 
2907
2289
 
2908
2290
class cmd_shell_complete(Command):
2909
2291
    """Show appropriate completions for context.
2910
2292
 
2911
 
    For a list of all available commands, say 'bzr shell-complete'.
2912
 
    """
 
2293
    For a list of all available commands, say 'bzr shell-complete'."""
2913
2294
    takes_args = ['context?']
2914
2295
    aliases = ['s-c']
2915
2296
    hidden = True
2923
2304
class cmd_fetch(Command):
2924
2305
    """Copy in history from another branch but don't merge it.
2925
2306
 
2926
 
    This is an internal method used for pull and merge.
2927
 
    """
 
2307
    This is an internal method used for pull and merge."""
2928
2308
    hidden = True
2929
2309
    takes_args = ['from_branch', 'to_branch']
2930
2310
    def run(self, from_branch, to_branch):
2931
2311
        from bzrlib.fetch import Fetcher
 
2312
        from bzrlib.branch import Branch
2932
2313
        from_b = Branch.open(from_branch)
2933
2314
        to_b = Branch.open(to_branch)
2934
2315
        Fetcher(to_b, from_b)
2936
2317
 
2937
2318
class cmd_missing(Command):
2938
2319
    """Show unmerged/unpulled revisions between two branches.
2939
 
    
2940
 
    OTHER_BRANCH may be local or remote.
2941
 
    """
2942
2320
 
2943
 
    _see_also = ['merge', 'pull']
 
2321
    OTHER_BRANCH may be local or remote."""
2944
2322
    takes_args = ['other_branch?']
2945
2323
    takes_options = [Option('reverse', 'Reverse the order of revisions'),
2946
2324
                     Option('mine-only', 
2947
2325
                            'Display changes in the local branch only'),
2948
 
                     Option('this' , 'same as --mine-only'),
2949
2326
                     Option('theirs-only', 
2950
 
                            'Display changes in the remote branch only'),
2951
 
                     Option('other', 'same as --theirs-only'),
 
2327
                            'Display changes in the remote branch only'), 
2952
2328
                     'log-format',
 
2329
                     'line',
 
2330
                     'long', 
 
2331
                     'short',
2953
2332
                     'show-ids',
2954
2333
                     'verbose'
2955
2334
                     ]
2956
 
    encoding_type = 'replace'
2957
2335
 
2958
 
    @display_command
2959
2336
    def run(self, other_branch=None, reverse=False, mine_only=False,
2960
2337
            theirs_only=False, log_format=None, long=False, short=False, line=False, 
2961
 
            show_ids=False, verbose=False, this=False, other=False):
2962
 
        from bzrlib.missing import find_unmerged, iter_log_revisions
 
2338
            show_ids=False, verbose=False):
 
2339
        from bzrlib.missing import find_unmerged, iter_log_data
2963
2340
        from bzrlib.log import log_formatter
2964
 
 
2965
 
        if this:
2966
 
          mine_only = this
2967
 
        if other:
2968
 
          theirs_only = other
2969
 
 
2970
 
        local_branch = Branch.open_containing(u".")[0]
 
2341
        local_branch = bzrlib.branch.Branch.open_containing(u".")[0]
2971
2342
        parent = local_branch.get_parent()
2972
2343
        if other_branch is None:
2973
2344
            other_branch = parent
2974
2345
            if other_branch is None:
2975
 
                raise errors.BzrCommandError("No peer location known or specified.")
2976
 
            display_url = urlutils.unescape_for_display(parent,
2977
 
                                                        self.outf.encoding)
2978
 
            print "Using last location: " + display_url
2979
 
 
2980
 
        remote_branch = Branch.open(other_branch)
 
2346
                raise BzrCommandError("No missing location known or specified.")
 
2347
            print "Using last location: " + local_branch.get_parent()
 
2348
        remote_branch = bzrlib.branch.Branch.open(other_branch)
2981
2349
        if remote_branch.base == local_branch.base:
2982
2350
            remote_branch = local_branch
2983
2351
        local_branch.lock_read()
2985
2353
            remote_branch.lock_read()
2986
2354
            try:
2987
2355
                local_extra, remote_extra = find_unmerged(local_branch, remote_branch)
2988
 
                if (log_format is None):
2989
 
                    log_format = log.log_formatter_registry.get_default(
2990
 
                        local_branch)
2991
 
                lf = log_format(to_file=self.outf,
2992
 
                                show_ids=show_ids,
2993
 
                                show_timezone='original')
 
2356
                if (log_format == None):
 
2357
                    default = bzrlib.config.BranchConfig(local_branch).log_format()
 
2358
                    log_format = get_log_format(long=long, short=short, line=line, default=default)
 
2359
                lf = log_formatter(log_format, sys.stdout,
 
2360
                                   show_ids=show_ids,
 
2361
                                   show_timezone='original')
2994
2362
                if reverse is False:
2995
2363
                    local_extra.reverse()
2996
2364
                    remote_extra.reverse()
2997
2365
                if local_extra and not theirs_only:
2998
2366
                    print "You have %d extra revision(s):" % len(local_extra)
2999
 
                    for revision in iter_log_revisions(local_extra, 
3000
 
                                        local_branch.repository,
3001
 
                                        verbose):
3002
 
                        lf.log_revision(revision)
 
2367
                    for data in iter_log_data(local_extra, local_branch.repository,
 
2368
                                              verbose):
 
2369
                        lf.show(*data)
3003
2370
                    printed_local = True
3004
2371
                else:
3005
2372
                    printed_local = False
3007
2374
                    if printed_local is True:
3008
2375
                        print "\n\n"
3009
2376
                    print "You are missing %d revision(s):" % len(remote_extra)
3010
 
                    for revision in iter_log_revisions(remote_extra, 
3011
 
                                        remote_branch.repository, 
3012
 
                                        verbose):
3013
 
                        lf.log_revision(revision)
 
2377
                    for data in iter_log_data(remote_extra, remote_branch.repository, 
 
2378
                                              verbose):
 
2379
                        lf.show(*data)
3014
2380
                if not remote_extra and not local_extra:
3015
2381
                    status_code = 0
3016
2382
                    print "Branches are up to date."
3039
2405
        import bzrlib.plugin
3040
2406
        from inspect import getdoc
3041
2407
        for name, plugin in bzrlib.plugin.all_plugins().items():
3042
 
            if getattr(plugin, '__path__', None) is not None:
 
2408
            if hasattr(plugin, '__path__'):
3043
2409
                print plugin.__path__[0]
3044
 
            elif getattr(plugin, '__file__', None) is not None:
 
2410
            elif hasattr(plugin, '__file__'):
3045
2411
                print plugin.__file__
3046
2412
            else:
3047
 
                print repr(plugin)
 
2413
                print `plugin`
3048
2414
                
3049
2415
            d = getdoc(plugin)
3050
2416
            if d:
3053
2419
 
3054
2420
class cmd_testament(Command):
3055
2421
    """Show testament (signing-form) of a revision."""
3056
 
    takes_options = ['revision',
3057
 
                     Option('long', help='Produce long-format testament'), 
3058
 
                     Option('strict', help='Produce a strict-format'
3059
 
                            ' testament')]
 
2422
    takes_options = ['revision', 'long']
3060
2423
    takes_args = ['branch?']
3061
2424
    @display_command
3062
 
    def run(self, branch=u'.', revision=None, long=False, strict=False):
3063
 
        from bzrlib.testament import Testament, StrictTestament
3064
 
        if strict is True:
3065
 
            testament_class = StrictTestament
3066
 
        else:
3067
 
            testament_class = Testament
 
2425
    def run(self, branch=u'.', revision=None, long=False):
 
2426
        from bzrlib.testament import Testament
3068
2427
        b = WorkingTree.open_containing(branch)[0].branch
3069
2428
        b.lock_read()
3070
2429
        try:
3072
2431
                rev_id = b.last_revision()
3073
2432
            else:
3074
2433
                rev_id = revision[0].in_history(b).rev_id
3075
 
            t = testament_class.from_revision(b.repository, rev_id)
 
2434
            t = Testament.from_revision(b.repository, rev_id)
3076
2435
            if long:
3077
2436
                sys.stdout.writelines(t.as_text_lines())
3078
2437
            else:
3093
2452
    # TODO: annotate directories; showing when each file was last changed
3094
2453
    # TODO: if the working copy is modified, show annotations on that 
3095
2454
    #       with new uncommitted lines marked
3096
 
    aliases = ['ann', 'blame', 'praise']
 
2455
    aliases = ['blame', 'praise']
3097
2456
    takes_args = ['filename']
3098
2457
    takes_options = [Option('all', help='show annotations on all lines'),
3099
2458
                     Option('long', help='show date in annotations'),
3100
 
                     'revision',
3101
 
                     'show-ids',
 
2459
                     'revision'
3102
2460
                     ]
3103
2461
 
3104
2462
    @display_command
3105
 
    def run(self, filename, all=False, long=False, revision=None,
3106
 
            show_ids=False):
 
2463
    def run(self, filename, all=False, long=False, revision=None):
3107
2464
        from bzrlib.annotate import annotate_file
3108
2465
        tree, relpath = WorkingTree.open_containing(filename)
3109
2466
        branch = tree.branch
3112
2469
            if revision is None:
3113
2470
                revision_id = branch.last_revision()
3114
2471
            elif len(revision) != 1:
3115
 
                raise errors.BzrCommandError('bzr annotate --revision takes exactly 1 argument')
 
2472
                raise BzrCommandError('bzr annotate --revision takes exactly 1 argument')
3116
2473
            else:
3117
2474
                revision_id = revision[0].in_history(branch).rev_id
3118
 
            file_id = tree.path2id(relpath)
3119
 
            if file_id is None:
3120
 
                raise errors.NotVersionedError(filename)
 
2475
            file_id = tree.inventory.path2id(relpath)
3121
2476
            tree = branch.repository.revision_tree(revision_id)
3122
2477
            file_version = tree.inventory[file_id].revision
3123
 
            annotate_file(branch, file_version, file_id, long, all, sys.stdout,
3124
 
                          show_ids=show_ids)
 
2478
            annotate_file(branch, file_version, file_id, long, all, sys.stdout)
3125
2479
        finally:
3126
2480
            branch.unlock()
3127
2481
 
3135
2489
    takes_options = ['revision']
3136
2490
    
3137
2491
    def run(self, revision_id_list=None, revision=None):
 
2492
        import bzrlib.config as config
3138
2493
        import bzrlib.gpg as gpg
3139
2494
        if revision_id_list is not None and revision is not None:
3140
 
            raise errors.BzrCommandError('You can only supply one of revision_id or --revision')
 
2495
            raise BzrCommandError('You can only supply one of revision_id or --revision')
3141
2496
        if revision_id_list is None and revision is None:
3142
 
            raise errors.BzrCommandError('You must supply either --revision or a revision_id')
 
2497
            raise BzrCommandError('You must supply either --revision or a revision_id')
3143
2498
        b = WorkingTree.open_containing(u'.')[0].branch
3144
 
        gpg_strategy = gpg.GPGStrategy(b.get_config())
 
2499
        gpg_strategy = gpg.GPGStrategy(config.BranchConfig(b))
3145
2500
        if revision_id_list is not None:
3146
2501
            for revision_id in revision_id_list:
3147
2502
                b.repository.sign_revision(revision_id, gpg_strategy)
3158
2513
                if to_revid is None:
3159
2514
                    to_revno = b.revno()
3160
2515
                if from_revno is None or to_revno is None:
3161
 
                    raise errors.BzrCommandError('Cannot sign a range of non-revision-history revisions')
 
2516
                    raise BzrCommandError('Cannot sign a range of non-revision-history revisions')
3162
2517
                for revno in range(from_revno, to_revno + 1):
3163
2518
                    b.repository.sign_revision(b.get_rev_id(revno), 
3164
2519
                                               gpg_strategy)
3165
2520
            else:
3166
 
                raise errors.BzrCommandError('Please supply either one revision, or a range.')
 
2521
                raise BzrCommandError('Please supply either one revision, or a range.')
3167
2522
 
3168
2523
 
3169
2524
class cmd_bind(Command):
3170
 
    """Convert the current branch into a checkout of the supplied branch.
 
2525
    """Bind the current branch to a master branch.
3171
2526
 
3172
 
    Once converted into a checkout, commits must succeed on the master branch
3173
 
    before they will be applied to the local branch.
 
2527
    After binding, commits must succeed on the master branch
 
2528
    before they are executed on the local one.
3174
2529
    """
3175
2530
 
3176
 
    _see_also = ['checkouts', 'unbind']
3177
 
    takes_args = ['location?']
 
2531
    takes_args = ['location']
3178
2532
    takes_options = []
3179
2533
 
3180
2534
    def run(self, location=None):
3181
2535
        b, relpath = Branch.open_containing(u'.')
3182
 
        if location is None:
3183
 
            try:
3184
 
                location = b.get_old_bound_location()
3185
 
            except errors.UpgradeRequired:
3186
 
                raise errors.BzrCommandError('No location supplied.  '
3187
 
                    'This format does not remember old locations.')
3188
 
            else:
3189
 
                if location is None:
3190
 
                    raise errors.BzrCommandError('No location supplied and no '
3191
 
                        'previous location known')
3192
2536
        b_other = Branch.open(location)
3193
2537
        try:
3194
2538
            b.bind(b_other)
3195
 
        except errors.DivergedBranches:
3196
 
            raise errors.BzrCommandError('These branches have diverged.'
3197
 
                                         ' Try merging, and then bind again.')
 
2539
        except DivergedBranches:
 
2540
            raise BzrCommandError('These branches have diverged.'
 
2541
                                  ' Try merging, and then bind again.')
3198
2542
 
3199
2543
 
3200
2544
class cmd_unbind(Command):
3201
 
    """Convert the current checkout into a regular branch.
 
2545
    """Unbind the current branch from its master branch.
3202
2546
 
3203
 
    After unbinding, the local branch is considered independent and subsequent
3204
 
    commits will be local only.
 
2547
    After unbinding, the local branch is considered independent.
 
2548
    All subsequent commits will be local.
3205
2549
    """
3206
2550
 
3207
 
    _see_also = ['checkouts', 'bind']
3208
2551
    takes_args = []
3209
2552
    takes_options = []
3210
2553
 
3211
2554
    def run(self):
3212
2555
        b, relpath = Branch.open_containing(u'.')
3213
2556
        if not b.unbind():
3214
 
            raise errors.BzrCommandError('Local branch is not bound')
3215
 
 
3216
 
 
3217
 
class cmd_uncommit(Command):
 
2557
            raise BzrCommandError('Local branch is not bound')
 
2558
 
 
2559
 
 
2560
class cmd_uncommit(bzrlib.commands.Command):
3218
2561
    """Remove the last committed revision.
3219
2562
 
3220
2563
    --verbose will print out what is being removed.
3226
2569
    """
3227
2570
 
3228
2571
    # TODO: jam 20060108 Add an option to allow uncommit to remove
3229
 
    # unreferenced information in 'branch-as-repository' branches.
 
2572
    # unreferenced information in 'branch-as-repostory' branches.
3230
2573
    # TODO: jam 20060108 Add the ability for uncommit to remove unreferenced
3231
2574
    # information in shared branches as well.
3232
 
    _see_also = ['commit']
3233
2575
    takes_options = ['verbose', 'revision',
3234
2576
                    Option('dry-run', help='Don\'t actually make changes'),
3235
2577
                    Option('force', help='Say yes to all questions.')]
3236
2578
    takes_args = ['location?']
3237
2579
    aliases = []
3238
2580
 
3239
 
    def run(self, location=None,
 
2581
    def run(self, location=None, 
3240
2582
            dry_run=False, verbose=False,
3241
2583
            revision=None, force=False):
3242
 
        from bzrlib.log import log_formatter, show_log
 
2584
        from bzrlib.branch import Branch
 
2585
        from bzrlib.log import log_formatter
3243
2586
        import sys
3244
2587
        from bzrlib.uncommit import uncommit
3245
2588
 
3253
2596
            tree = None
3254
2597
            b = control.open_branch()
3255
2598
 
3256
 
        rev_id = None
3257
2599
        if revision is None:
3258
2600
            revno = b.revno()
 
2601
            rev_id = b.last_revision()
3259
2602
        else:
3260
 
            # 'bzr uncommit -r 10' actually means uncommit
3261
 
            # so that the final tree is at revno 10.
3262
 
            # but bzrlib.uncommit.uncommit() actually uncommits
3263
 
            # the revisions that are supplied.
3264
 
            # So we need to offset it by one
3265
 
            revno = revision[0].in_history(b).revno+1
3266
 
 
3267
 
        if revno <= b.revno():
3268
 
            rev_id = b.get_rev_id(revno)
 
2603
            revno, rev_id = revision[0].in_history(b)
3269
2604
        if rev_id is None:
3270
 
            self.outf.write('No revisions to uncommit.\n')
3271
 
            return 1
3272
 
 
3273
 
        lf = log_formatter('short',
3274
 
                           to_file=self.outf,
3275
 
                           show_timezone='original')
3276
 
 
3277
 
        show_log(b,
3278
 
                 lf,
3279
 
                 verbose=False,
3280
 
                 direction='forward',
3281
 
                 start_revision=revno,
3282
 
                 end_revision=b.revno())
 
2605
            print 'No revisions to uncommit.'
 
2606
 
 
2607
        for r in range(revno, b.revno()+1):
 
2608
            rev_id = b.get_rev_id(r)
 
2609
            lf = log_formatter('short', to_file=sys.stdout,show_timezone='original')
 
2610
            lf.show(r, b.repository.get_revision(rev_id), None)
3283
2611
 
3284
2612
        if dry_run:
3285
2613
            print 'Dry-run, pretending to remove the above revisions.'
3320
2648
            pass
3321
2649
        
3322
2650
 
3323
 
class cmd_wait_until_signalled(Command):
3324
 
    """Test helper for test_start_and_stop_bzr_subprocess_send_signal.
3325
 
 
3326
 
    This just prints a line to signal when it is ready, then blocks on stdin.
3327
 
    """
3328
 
 
3329
 
    hidden = True
3330
 
 
3331
 
    def run(self):
3332
 
        sys.stdout.write("running\n")
3333
 
        sys.stdout.flush()
3334
 
        sys.stdin.readline()
3335
 
 
3336
 
 
3337
 
class cmd_serve(Command):
3338
 
    """Run the bzr server."""
3339
 
 
3340
 
    aliases = ['server']
3341
 
 
3342
 
    takes_options = [
3343
 
        Option('inet',
3344
 
               help='serve on stdin/out for use from inetd or sshd'),
3345
 
        Option('port',
3346
 
               help='listen for connections on nominated port of the form '
3347
 
                    '[hostname:]portnumber. Passing 0 as the port number will '
3348
 
                    'result in a dynamically allocated port. Default port is '
3349
 
                    '4155.',
3350
 
               type=str),
3351
 
        Option('directory',
3352
 
               help='serve contents of directory',
3353
 
               type=unicode),
3354
 
        Option('allow-writes',
3355
 
               help='By default the server is a readonly server. Supplying '
3356
 
                    '--allow-writes enables write access to the contents of '
3357
 
                    'the served directory and below. '
3358
 
                ),
3359
 
        ]
3360
 
 
3361
 
    def run(self, port=None, inet=False, directory=None, allow_writes=False):
3362
 
        from bzrlib.smart import medium, server
3363
 
        from bzrlib.transport import get_transport
3364
 
        from bzrlib.transport.chroot import ChrootServer
3365
 
        from bzrlib.transport.remote import BZR_DEFAULT_PORT, BZR_DEFAULT_INTERFACE
3366
 
        if directory is None:
3367
 
            directory = os.getcwd()
3368
 
        url = urlutils.local_path_to_url(directory)
3369
 
        if not allow_writes:
3370
 
            url = 'readonly+' + url
3371
 
        chroot_server = ChrootServer(get_transport(url))
3372
 
        chroot_server.setUp()
3373
 
        t = get_transport(chroot_server.get_url())
3374
 
        if inet:
3375
 
            smart_server = medium.SmartServerPipeStreamMedium(
3376
 
                sys.stdin, sys.stdout, t)
3377
 
        else:
3378
 
            host = BZR_DEFAULT_INTERFACE
3379
 
            if port is None:
3380
 
                port = BZR_DEFAULT_PORT
3381
 
            else:
3382
 
                if ':' in port:
3383
 
                    host, port = port.split(':')
3384
 
                port = int(port)
3385
 
            smart_server = server.SmartTCPServer(t, host=host, port=port)
3386
 
            print 'listening on port: ', smart_server.port
3387
 
            sys.stdout.flush()
3388
 
        # for the duration of this server, no UI output is permitted.
3389
 
        # note that this may cause problems with blackbox tests. This should
3390
 
        # be changed with care though, as we dont want to use bandwidth sending
3391
 
        # progress over stderr to smart server clients!
3392
 
        old_factory = ui.ui_factory
3393
 
        try:
3394
 
            ui.ui_factory = ui.SilentUIFactory()
3395
 
            smart_server.serve()
3396
 
        finally:
3397
 
            ui.ui_factory = old_factory
3398
 
 
3399
 
 
3400
 
class cmd_join(Command):
3401
 
    """Combine a subtree into its containing tree.
3402
 
    
3403
 
    This command is for experimental use only.  It requires the target tree
3404
 
    to be in dirstate-with-subtree format, which cannot be converted into
3405
 
    earlier formats.
3406
 
 
3407
 
    The TREE argument should be an independent tree, inside another tree, but
3408
 
    not part of it.  (Such trees can be produced by "bzr split", but also by
3409
 
    running "bzr branch" with the target inside a tree.)
3410
 
 
3411
 
    The result is a combined tree, with the subtree no longer an independant
3412
 
    part.  This is marked as a merge of the subtree into the containing tree,
3413
 
    and all history is preserved.
3414
 
 
3415
 
    If --reference is specified, the subtree retains its independence.  It can
3416
 
    be branched by itself, and can be part of multiple projects at the same
3417
 
    time.  But operations performed in the containing tree, such as commit
3418
 
    and merge, will recurse into the subtree.
3419
 
    """
3420
 
 
3421
 
    _see_also = ['split']
3422
 
    takes_args = ['tree']
3423
 
    takes_options = [Option('reference', 'join by reference')]
3424
 
    hidden = True
3425
 
 
3426
 
    def run(self, tree, reference=False):
3427
 
        sub_tree = WorkingTree.open(tree)
3428
 
        parent_dir = osutils.dirname(sub_tree.basedir)
3429
 
        containing_tree = WorkingTree.open_containing(parent_dir)[0]
3430
 
        repo = containing_tree.branch.repository
3431
 
        if not repo.supports_rich_root():
3432
 
            raise errors.BzrCommandError(
3433
 
                "Can't join trees because %s doesn't support rich root data.\n"
3434
 
                "You can use bzr upgrade on the repository."
3435
 
                % (repo,))
3436
 
        if reference:
3437
 
            try:
3438
 
                containing_tree.add_reference(sub_tree)
3439
 
            except errors.BadReferenceTarget, e:
3440
 
                # XXX: Would be better to just raise a nicely printable
3441
 
                # exception from the real origin.  Also below.  mbp 20070306
3442
 
                raise errors.BzrCommandError("Cannot join %s.  %s" %
3443
 
                                             (tree, e.reason))
3444
 
        else:
3445
 
            try:
3446
 
                containing_tree.subsume(sub_tree)
3447
 
            except errors.BadSubsumeSource, e:
3448
 
                raise errors.BzrCommandError("Cannot join %s.  %s" % 
3449
 
                                             (tree, e.reason))
3450
 
 
3451
 
 
3452
 
class cmd_split(Command):
3453
 
    """Split a tree into two trees.
3454
 
 
3455
 
    This command is for experimental use only.  It requires the target tree
3456
 
    to be in dirstate-with-subtree format, which cannot be converted into
3457
 
    earlier formats.
3458
 
 
3459
 
    The TREE argument should be a subdirectory of a working tree.  That
3460
 
    subdirectory will be converted into an independent tree, with its own
3461
 
    branch.  Commits in the top-level tree will not apply to the new subtree.
3462
 
    If you want that behavior, do "bzr join --reference TREE".
3463
 
    """
3464
 
 
3465
 
    _see_also = ['join']
3466
 
    takes_args = ['tree']
3467
 
 
3468
 
    hidden = True
3469
 
 
3470
 
    def run(self, tree):
3471
 
        containing_tree, subdir = WorkingTree.open_containing(tree)
3472
 
        sub_id = containing_tree.path2id(subdir)
3473
 
        if sub_id is None:
3474
 
            raise errors.NotVersionedError(subdir)
3475
 
        try:
3476
 
            containing_tree.extract(sub_id)
3477
 
        except errors.RootNotRich:
3478
 
            raise errors.UpgradeRequired(containing_tree.branch.base)
3479
 
 
3480
 
 
3481
 
 
3482
 
class cmd_merge_directive(Command):
3483
 
    """Generate a merge directive for auto-merge tools.
3484
 
 
3485
 
    A directive requests a merge to be performed, and also provides all the
3486
 
    information necessary to do so.  This means it must either include a
3487
 
    revision bundle, or the location of a branch containing the desired
3488
 
    revision.
3489
 
 
3490
 
    A submit branch (the location to merge into) must be supplied the first
3491
 
    time the command is issued.  After it has been supplied once, it will
3492
 
    be remembered as the default.
3493
 
 
3494
 
    A public branch is optional if a revision bundle is supplied, but required
3495
 
    if --diff or --plain is specified.  It will be remembered as the default
3496
 
    after the first use.
3497
 
    """
3498
 
 
3499
 
    takes_args = ['submit_branch?', 'public_branch?']
3500
 
 
3501
 
    takes_options = [
3502
 
        RegistryOption.from_kwargs('patch-type',
3503
 
            'The type of patch to include in the directive',
3504
 
            title='Patch type', value_switches=True, enum_switch=False,
3505
 
            bundle='Bazaar revision bundle (default)',
3506
 
            diff='Normal unified diff',
3507
 
            plain='No patch, just directive'),
3508
 
        Option('sign', help='GPG-sign the directive'), 'revision',
3509
 
        Option('mail-to', type=str,
3510
 
            help='Instead of printing the directive, email to this address'),
3511
 
        Option('message', type=str, short_name='m',
3512
 
            help='Message to use when committing this merge')
3513
 
        ]
3514
 
 
3515
 
    encoding_type = 'exact'
3516
 
 
3517
 
    def run(self, submit_branch=None, public_branch=None, patch_type='bundle',
3518
 
            sign=False, revision=None, mail_to=None, message=None):
3519
 
        from bzrlib.revision import ensure_null, NULL_REVISION
3520
 
        if patch_type == 'plain':
3521
 
            patch_type = None
3522
 
        branch = Branch.open('.')
3523
 
        stored_submit_branch = branch.get_submit_branch()
3524
 
        if submit_branch is None:
3525
 
            submit_branch = stored_submit_branch
3526
 
        else:
3527
 
            if stored_submit_branch is None:
3528
 
                branch.set_submit_branch(submit_branch)
3529
 
        if submit_branch is None:
3530
 
            submit_branch = branch.get_parent()
3531
 
        if submit_branch is None:
3532
 
            raise errors.BzrCommandError('No submit branch specified or known')
3533
 
 
3534
 
        stored_public_branch = branch.get_public_branch()
3535
 
        if public_branch is None:
3536
 
            public_branch = stored_public_branch
3537
 
        elif stored_public_branch is None:
3538
 
            branch.set_public_branch(public_branch)
3539
 
        if patch_type != "bundle" and public_branch is None:
3540
 
            raise errors.BzrCommandError('No public branch specified or'
3541
 
                                         ' known')
3542
 
        if revision is not None:
3543
 
            if len(revision) != 1:
3544
 
                raise errors.BzrCommandError('bzr merge-directive takes '
3545
 
                    'exactly one revision identifier')
3546
 
            else:
3547
 
                revision_id = revision[0].in_history(branch).rev_id
3548
 
        else:
3549
 
            revision_id = branch.last_revision()
3550
 
        revision_id = ensure_null(revision_id)
3551
 
        if revision_id == NULL_REVISION:
3552
 
            raise errors.BzrCommandError('No revisions to bundle.')
3553
 
        directive = merge_directive.MergeDirective.from_objects(
3554
 
            branch.repository, revision_id, time.time(),
3555
 
            osutils.local_time_offset(), submit_branch,
3556
 
            public_branch=public_branch, patch_type=patch_type,
3557
 
            message=message)
3558
 
        if mail_to is None:
3559
 
            if sign:
3560
 
                self.outf.write(directive.to_signed(branch))
3561
 
            else:
3562
 
                self.outf.writelines(directive.to_lines())
3563
 
        else:
3564
 
            message = directive.to_email(mail_to, branch, sign)
3565
 
            s = SMTPConnection(branch.get_config())
3566
 
            s.send_email(message)
3567
 
 
3568
 
 
3569
 
class cmd_tag(Command):
3570
 
    """Create a tag naming a revision.
3571
 
    
3572
 
    Tags give human-meaningful names to revisions.  Commands that take a -r
3573
 
    (--revision) option can be given -rtag:X, where X is any previously
3574
 
    created tag.
3575
 
 
3576
 
    Tags are stored in the branch.  Tags are copied from one branch to another
3577
 
    along when you branch, push, pull or merge.
3578
 
 
3579
 
    It is an error to give a tag name that already exists unless you pass 
3580
 
    --force, in which case the tag is moved to point to the new revision.
3581
 
    """
3582
 
 
3583
 
    _see_also = ['commit', 'tags']
3584
 
    takes_args = ['tag_name']
3585
 
    takes_options = [
3586
 
        Option('delete',
3587
 
            help='Delete this tag rather than placing it.',
3588
 
            ),
3589
 
        Option('directory',
3590
 
            help='Branch in which to place the tag.',
3591
 
            short_name='d',
3592
 
            type=unicode,
3593
 
            ),
3594
 
        Option('force',
3595
 
            help='Replace existing tags',
3596
 
            ),
3597
 
        'revision',
3598
 
        ]
3599
 
 
3600
 
    def run(self, tag_name,
3601
 
            delete=None,
3602
 
            directory='.',
3603
 
            force=None,
3604
 
            revision=None,
3605
 
            ):
3606
 
        branch, relpath = Branch.open_containing(directory)
3607
 
        branch.lock_write()
3608
 
        try:
3609
 
            if delete:
3610
 
                branch.tags.delete_tag(tag_name)
3611
 
                self.outf.write('Deleted tag %s.\n' % tag_name)
3612
 
            else:
3613
 
                if revision:
3614
 
                    if len(revision) != 1:
3615
 
                        raise errors.BzrCommandError(
3616
 
                            "Tags can only be placed on a single revision, "
3617
 
                            "not on a range")
3618
 
                    revision_id = revision[0].in_history(branch).rev_id
3619
 
                else:
3620
 
                    revision_id = branch.last_revision()
3621
 
                if (not force) and branch.tags.has_tag(tag_name):
3622
 
                    raise errors.TagAlreadyExists(tag_name)
3623
 
                branch.tags.set_tag(tag_name, revision_id)
3624
 
                self.outf.write('Created tag %s.\n' % tag_name)
3625
 
        finally:
3626
 
            branch.unlock()
3627
 
 
3628
 
 
3629
 
class cmd_tags(Command):
3630
 
    """List tags.
3631
 
 
3632
 
    This tag shows a table of tag names and the revisions they reference.
3633
 
    """
3634
 
 
3635
 
    _see_also = ['tag']
3636
 
    takes_options = [
3637
 
        Option('directory',
3638
 
            help='Branch whose tags should be displayed',
3639
 
            short_name='d',
3640
 
            type=unicode,
3641
 
            ),
3642
 
    ]
3643
 
 
3644
 
    @display_command
3645
 
    def run(self,
3646
 
            directory='.',
3647
 
            ):
3648
 
        branch, relpath = Branch.open_containing(directory)
3649
 
        for tag_name, target in sorted(branch.tags.get_tag_dict().items()):
3650
 
            self.outf.write('%-20s %s\n' % (tag_name, target))
3651
 
 
3652
2651
 
3653
2652
# command-line interpretation helper for merge-related commands
3654
 
def _merge_helper(other_revision, base_revision,
3655
 
                  check_clean=True, ignore_zero=False,
3656
 
                  this_dir=None, backup_files=False,
3657
 
                  merge_type=None,
3658
 
                  file_list=None, show_base=False, reprocess=False,
3659
 
                  pull=False,
3660
 
                  pb=DummyProgress(),
3661
 
                  change_reporter=None,
3662
 
                  other_rev_id=None):
 
2653
def merge(other_revision, base_revision,
 
2654
          check_clean=True, ignore_zero=False,
 
2655
          this_dir=None, backup_files=False, merge_type=Merge3Merger,
 
2656
          file_list=None, show_base=False, reprocess=False,
 
2657
          pb=DummyProgress()):
3663
2658
    """Merge changes into a tree.
3664
2659
 
3665
2660
    base_revision
3687
2682
    clients might prefer to call merge.merge_inner(), which has less magic 
3688
2683
    behavior.
3689
2684
    """
3690
 
    # Loading it late, so that we don't always have to import bzrlib.merge
3691
 
    if merge_type is None:
3692
 
        merge_type = _mod_merge.Merge3Merger
 
2685
    from bzrlib.merge import Merger
3693
2686
    if this_dir is None:
3694
2687
        this_dir = u'.'
3695
2688
    this_tree = WorkingTree.open_containing(this_dir)[0]
3696
 
    if show_base and not merge_type is _mod_merge.Merge3Merger:
3697
 
        raise errors.BzrCommandError("Show-base is not supported for this merge"
3698
 
                                     " type. %s" % merge_type)
 
2689
    if show_base and not merge_type is Merge3Merger:
 
2690
        raise BzrCommandError("Show-base is not supported for this merge"
 
2691
                              " type. %s" % merge_type)
3699
2692
    if reprocess and not merge_type.supports_reprocess:
3700
 
        raise errors.BzrCommandError("Conflict reduction is not supported for merge"
3701
 
                                     " type %s." % merge_type)
 
2693
        raise BzrCommandError("Conflict reduction is not supported for merge"
 
2694
                              " type %s." % merge_type)
3702
2695
    if reprocess and show_base:
3703
 
        raise errors.BzrCommandError("Cannot do conflict reduction and show base.")
3704
 
    # TODO: jam 20070226 We should really lock these trees earlier. However, we
3705
 
    #       only want to take out a lock_tree_write() if we don't have to pull
3706
 
    #       any ancestry. But merge might fetch ancestry in the middle, in
3707
 
    #       which case we would need a lock_write().
3708
 
    #       Because we cannot upgrade locks, for now we live with the fact that
3709
 
    #       the tree will be locked multiple times during a merge. (Maybe
3710
 
    #       read-only some of the time, but it means things will get read
3711
 
    #       multiple times.)
 
2696
        raise BzrCommandError("Cannot do conflict reduction and show base.")
3712
2697
    try:
3713
 
        merger = _mod_merge.Merger(this_tree.branch, this_tree=this_tree,
3714
 
                                   pb=pb, change_reporter=change_reporter)
 
2698
        merger = Merger(this_tree.branch, this_tree=this_tree, pb=pb)
3715
2699
        merger.pp = ProgressPhase("Merge phase", 5, pb)
3716
2700
        merger.pp.next_phase()
3717
2701
        merger.check_basis(check_clean)
3718
 
        if other_rev_id is not None:
3719
 
            merger.set_other_revision(other_rev_id, this_tree.branch)
3720
 
        else:
3721
 
            merger.set_other(other_revision)
 
2702
        merger.set_other(other_revision)
3722
2703
        merger.pp.next_phase()
3723
2704
        merger.set_base(base_revision)
3724
2705
        if merger.base_rev_id == merger.other_rev_id:
3725
2706
            note('Nothing to do.')
3726
2707
            return 0
3727
 
        if file_list is None:
3728
 
            if pull and merger.base_rev_id == merger.this_rev_id:
3729
 
                # FIXME: deduplicate with pull
3730
 
                result = merger.this_tree.pull(merger.this_branch,
3731
 
                        False, merger.other_rev_id)
3732
 
                if result.old_revid == result.new_revid:
3733
 
                    note('No revisions to pull.')
3734
 
                else:
3735
 
                    note('Now on revision %d.' % result.new_revno)
3736
 
                return 0
3737
2708
        merger.backup_files = backup_files
3738
2709
        merger.merge_type = merge_type 
3739
2710
        merger.set_interesting_files(file_list)
3747
2718
    return conflicts
3748
2719
 
3749
2720
 
3750
 
def _create_prefix(cur_transport):
3751
 
    needed = [cur_transport]
3752
 
    # Recurse upwards until we can create a directory successfully
3753
 
    while True:
3754
 
        new_transport = cur_transport.clone('..')
3755
 
        if new_transport.base == cur_transport.base:
3756
 
            raise errors.BzrCommandError("Failed to create path"
3757
 
                                         " prefix for %s."
3758
 
                                         % location)
3759
 
        try:
3760
 
            new_transport.mkdir('.')
3761
 
        except errors.NoSuchFile:
3762
 
            needed.append(new_transport)
3763
 
            cur_transport = new_transport
3764
 
        else:
3765
 
            break
3766
 
 
3767
 
    # Now we only need to create child directories
3768
 
    while needed:
3769
 
        cur_transport = needed.pop()
3770
 
        cur_transport.ensure_base()
3771
 
 
3772
 
# Compatibility
3773
 
merge = _merge_helper
3774
 
 
3775
 
 
3776
2721
# these get imported and then picked up by the scan for cmd_*
3777
2722
# TODO: Some more consistent way to split command definitions across files;
3778
2723
# we do need to load at least some information about them to know of 
3779
2724
# aliases.  ideally we would avoid loading the implementation until the
3780
2725
# details were needed.
3781
 
from bzrlib.cmd_version_info import cmd_version_info
3782
2726
from bzrlib.conflicts import cmd_resolve, cmd_conflicts, restore
3783
2727
from bzrlib.bundle.commands import cmd_bundle_revisions
3784
2728
from bzrlib.sign_my_commits import cmd_sign_my_commits
3785
 
from bzrlib.weave_commands import cmd_versionedfile_list, cmd_weave_join, \
 
2729
from bzrlib.weave_commands import cmd_weave_list, cmd_weave_join, \
3786
2730
        cmd_weave_plan_merge, cmd_weave_merge_text