~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Robert Collins
  • Date: 2007-07-04 08:08:13 UTC
  • mfrom: (2572 +trunk)
  • mto: This revision was merged to the branch mainline in revision 2587.
  • Revision ID: robertc@robertcollins.net-20070704080813-wzebx0r88fvwj5rq
Merge bzr.dev.

Show diffs side-by-side

added added

removed removed

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