/brz/remove-bazaar

To get this branch, use:
bzr branch http://gegoxaren.bato24.eu/bzr/brz/remove-bazaar

« back to all changes in this revision

Viewing changes to bzrlib/builtins.py

  • Committer: Vincent Ladeuil
  • Date: 2007-09-24 15:01:26 UTC
  • mfrom: (2853 +trunk)
  • mto: (2885.1.1 140432)
  • mto: This revision was merged to the branch mainline in revision 2886.
  • Revision ID: v.ladeuil+lp@free.fr-20070924150126-nll7i0385kisklyj
Merge bzr.dev

Show diffs side-by-side

added added

removed removed

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