~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Robert Collins
  • Date: 2005-08-24 06:53:07 UTC
  • mto: (974.1.50) (1185.1.10) (1092.3.1)
  • mto: This revision was merged to the branch mainline in revision 1139.
  • Revision ID: robertc@robertcollins.net-20050824065307-bca8ae89734a53f8
merge from mpool

Show diffs side-by-side

added added

removed removed

Lines of Context:
15
15
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
16
16
 
17
17
 
18
 
 
19
 
import sys, os, time, os.path
20
 
from sets import Set
 
18
# TODO: Split the command framework away from the actual commands.
 
19
 
 
20
# TODO: probably should say which arguments are candidates for glob
 
21
# expansion on windows and do that at the command level.
 
22
 
 
23
# TODO: Help messages for options.
 
24
 
 
25
# TODO: Define arguments by objects, rather than just using names.
 
26
# Those objects can specify the expected type of the argument, which
 
27
# would help with validation and shell completion.
 
28
 
 
29
 
 
30
import sys
 
31
import os
21
32
 
22
33
import bzrlib
23
 
from bzrlib.trace import mutter, note, log_error
24
 
from bzrlib.errors import bailout, BzrError, BzrCheckError, BzrCommandError
25
 
from bzrlib.osutils import quotefn, pumpfile, isdir, isfile
26
 
from bzrlib.tree import RevisionTree, EmptyTree, Tree
27
 
from bzrlib.revision import Revision
28
 
from bzrlib import Branch, Inventory, InventoryEntry, ScratchBranch, BZRDIR, \
29
 
     format_date
 
34
from bzrlib.trace import mutter, note, log_error, warning
 
35
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError
 
36
from bzrlib.branch import find_branch
 
37
from bzrlib import BZRDIR
 
38
 
 
39
 
 
40
plugin_cmds = {}
 
41
 
 
42
 
 
43
def register_command(cmd):
 
44
    "Utility function to help register a command"
 
45
    global plugin_cmds
 
46
    k = cmd.__name__
 
47
    if k.startswith("cmd_"):
 
48
        k_unsquished = _unsquish_command_name(k)
 
49
    else:
 
50
        k_unsquished = k
 
51
    if not plugin_cmds.has_key(k_unsquished):
 
52
        plugin_cmds[k_unsquished] = cmd
 
53
    else:
 
54
        log_error('Two plugins defined the same command: %r' % k)
 
55
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
30
56
 
31
57
 
32
58
def _squish_command_name(cmd):
37
63
    assert cmd.startswith("cmd_")
38
64
    return cmd[4:].replace('_','-')
39
65
 
40
 
def get_all_cmds():
41
 
    """Return canonical name and class for all registered commands."""
 
66
 
 
67
def _parse_revision_str(revstr):
 
68
    """This handles a revision string -> revno.
 
69
 
 
70
    This always returns a list.  The list will have one element for 
 
71
 
 
72
    It supports integers directly, but everything else it
 
73
    defers for passing to Branch.get_revision_info()
 
74
 
 
75
    >>> _parse_revision_str('234')
 
76
    [234]
 
77
    >>> _parse_revision_str('234..567')
 
78
    [234, 567]
 
79
    >>> _parse_revision_str('..')
 
80
    [None, None]
 
81
    >>> _parse_revision_str('..234')
 
82
    [None, 234]
 
83
    >>> _parse_revision_str('234..')
 
84
    [234, None]
 
85
    >>> _parse_revision_str('234..456..789') # Maybe this should be an error
 
86
    [234, 456, 789]
 
87
    >>> _parse_revision_str('234....789') # Error?
 
88
    [234, None, 789]
 
89
    >>> _parse_revision_str('revid:test@other.com-234234')
 
90
    ['revid:test@other.com-234234']
 
91
    >>> _parse_revision_str('revid:test@other.com-234234..revid:test@other.com-234235')
 
92
    ['revid:test@other.com-234234', 'revid:test@other.com-234235']
 
93
    >>> _parse_revision_str('revid:test@other.com-234234..23')
 
94
    ['revid:test@other.com-234234', 23]
 
95
    >>> _parse_revision_str('date:2005-04-12')
 
96
    ['date:2005-04-12']
 
97
    >>> _parse_revision_str('date:2005-04-12 12:24:33')
 
98
    ['date:2005-04-12 12:24:33']
 
99
    >>> _parse_revision_str('date:2005-04-12T12:24:33')
 
100
    ['date:2005-04-12T12:24:33']
 
101
    >>> _parse_revision_str('date:2005-04-12,12:24:33')
 
102
    ['date:2005-04-12,12:24:33']
 
103
    >>> _parse_revision_str('-5..23')
 
104
    [-5, 23]
 
105
    >>> _parse_revision_str('-5')
 
106
    [-5]
 
107
    >>> _parse_revision_str('123a')
 
108
    ['123a']
 
109
    >>> _parse_revision_str('abc')
 
110
    ['abc']
 
111
    """
 
112
    import re
 
113
    old_format_re = re.compile('\d*:\d*')
 
114
    m = old_format_re.match(revstr)
 
115
    if m:
 
116
        warning('Colon separator for revision numbers is deprecated.'
 
117
                ' Use .. instead')
 
118
        revs = []
 
119
        for rev in revstr.split(':'):
 
120
            if rev:
 
121
                revs.append(int(rev))
 
122
            else:
 
123
                revs.append(None)
 
124
        return revs
 
125
    revs = []
 
126
    for x in revstr.split('..'):
 
127
        if not x:
 
128
            revs.append(None)
 
129
        else:
 
130
            try:
 
131
                revs.append(int(x))
 
132
            except ValueError:
 
133
                revs.append(x)
 
134
    return revs
 
135
 
 
136
 
 
137
def get_merge_type(typestring):
 
138
    """Attempt to find the merge class/factory associated with a string."""
 
139
    from merge import merge_types
 
140
    try:
 
141
        return merge_types[typestring][0]
 
142
    except KeyError:
 
143
        templ = '%s%%7s: %%s' % (' '*12)
 
144
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
 
145
        type_list = '\n'.join(lines)
 
146
        msg = "No known merge type %s. Supported types are:\n%s" %\
 
147
            (typestring, type_list)
 
148
        raise BzrCommandError(msg)
 
149
    
 
150
 
 
151
def get_merge_type(typestring):
 
152
    """Attempt to find the merge class/factory associated with a string."""
 
153
    from merge import merge_types
 
154
    try:
 
155
        return merge_types[typestring][0]
 
156
    except KeyError:
 
157
        templ = '%s%%7s: %%s' % (' '*12)
 
158
        lines = [templ % (f[0], f[1][1]) for f in merge_types.iteritems()]
 
159
        type_list = '\n'.join(lines)
 
160
        msg = "No known merge type %s. Supported types are:\n%s" %\
 
161
            (typestring, type_list)
 
162
        raise BzrCommandError(msg)
 
163
    
 
164
 
 
165
 
 
166
def _get_cmd_dict(plugins_override=True):
 
167
    d = {}
42
168
    for k, v in globals().iteritems():
43
169
        if k.startswith("cmd_"):
44
 
            yield _unsquish_command_name(k), v
45
 
 
46
 
def get_cmd_class(cmd):
 
170
            d[_unsquish_command_name(k)] = v
 
171
    # If we didn't load plugins, the plugin_cmds dict will be empty
 
172
    if plugins_override:
 
173
        d.update(plugin_cmds)
 
174
    else:
 
175
        d2 = plugin_cmds.copy()
 
176
        d2.update(d)
 
177
        d = d2
 
178
    return d
 
179
 
 
180
    
 
181
def get_all_cmds(plugins_override=True):
 
182
    """Return canonical name and class for all registered commands."""
 
183
    for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
 
184
        yield k,v
 
185
 
 
186
 
 
187
def get_cmd_class(cmd, plugins_override=True):
47
188
    """Return the canonical name and command class for a command.
48
189
    """
49
190
    cmd = str(cmd)                      # not unicode
50
191
 
51
192
    # first look up this command under the specified name
 
193
    cmds = _get_cmd_dict(plugins_override=plugins_override)
52
194
    try:
53
 
        return cmd, globals()[_squish_command_name(cmd)]
 
195
        return cmd, cmds[cmd]
54
196
    except KeyError:
55
197
        pass
56
198
 
57
199
    # look for any command which claims this as an alias
58
 
    for cmdname, cmdclass in get_all_cmds():
 
200
    for cmdname, cmdclass in cmds.iteritems():
59
201
        if cmd in cmdclass.aliases:
60
202
            return cmdname, cmdclass
61
203
 
66
208
    raise BzrCommandError("unknown command %r" % cmd)
67
209
 
68
210
 
69
 
class Command:
 
211
class Command(object):
70
212
    """Base class for commands.
71
213
 
72
214
    The docstring for an actual command should give a single-line
98
240
        assert isinstance(arguments, dict)
99
241
        cmdargs = options.copy()
100
242
        cmdargs.update(arguments)
101
 
        assert self.__doc__ != Command.__doc__, \
102
 
               ("No help message set for %r" % self)
 
243
        if self.__doc__ == Command.__doc__:
 
244
            from warnings import warn
 
245
            warn("No help message set for %r" % self)
103
246
        self.status = self.run(**cmdargs)
 
247
        if self.status is None:
 
248
            self.status = 0
104
249
 
105
250
    
106
251
    def run(self):
118
263
class ExternalCommand(Command):
119
264
    """Class to wrap external commands.
120
265
 
121
 
    We cheat a little here, when get_cmd_class() calls us we actually give it back
122
 
    an object we construct that has the appropriate path, help, options etc for the
123
 
    specified command.
124
 
 
125
 
    When run_bzr() tries to instantiate that 'class' it gets caught by the __call__
126
 
    method, which we override to call the Command.__init__ method. That then calls
127
 
    our run method which is pretty straight forward.
128
 
 
129
 
    The only wrinkle is that we have to map bzr's dictionary of options and arguments
130
 
    back into command line options and arguments for the script.
 
266
    We cheat a little here, when get_cmd_class() calls us we actually
 
267
    give it back an object we construct that has the appropriate path,
 
268
    help, options etc for the specified command.
 
269
 
 
270
    When run_bzr() tries to instantiate that 'class' it gets caught by
 
271
    the __call__ method, which we override to call the Command.__init__
 
272
    method. That then calls our run method which is pretty straight
 
273
    forward.
 
274
 
 
275
    The only wrinkle is that we have to map bzr's dictionary of options
 
276
    and arguments back into command line options and arguments for the
 
277
    script.
131
278
    """
132
279
 
133
280
    def find_command(cls, cmd):
 
281
        import os.path
134
282
        bzrpath = os.environ.get('BZRPATH', '')
135
283
 
136
 
        for dir in bzrpath.split(':'):
 
284
        for dir in bzrpath.split(os.pathsep):
137
285
            path = os.path.join(dir, cmd)
138
286
            if os.path.isfile(path):
139
287
                return ExternalCommand(path)
145
293
    def __init__(self, path):
146
294
        self.path = path
147
295
 
148
 
        # TODO: If either of these fail, we should detect that and
149
 
        # assume that path is not really a bzr plugin after all.
150
 
 
151
296
        pipe = os.popen('%s --bzr-usage' % path, 'r')
152
297
        self.takes_options = pipe.readline().split()
 
298
 
 
299
        for opt in self.takes_options:
 
300
            if not opt in OPTIONS:
 
301
                raise BzrError("Unknown option '%s' returned by external command %s"
 
302
                               % (opt, path))
 
303
 
 
304
        # TODO: Is there any way to check takes_args is valid here?
153
305
        self.takes_args = pipe.readline().split()
154
 
        pipe.close()
 
306
 
 
307
        if pipe.close() is not None:
 
308
            raise BzrError("Failed funning '%s --bzr-usage'" % path)
155
309
 
156
310
        pipe = os.popen('%s --bzr-help' % path, 'r')
157
311
        self.__doc__ = pipe.read()
158
 
        pipe.close()
 
312
        if pipe.close() is not None:
 
313
            raise BzrError("Failed funning '%s --bzr-help'" % path)
159
314
 
160
315
    def __call__(self, options, arguments):
161
316
        Command.__init__(self, options, arguments)
168
323
        keys = kargs.keys()
169
324
        keys.sort()
170
325
        for name in keys:
 
326
            optname = name.replace('_','-')
171
327
            value = kargs[name]
172
 
            if OPTIONS.has_key(name):
 
328
            if OPTIONS.has_key(optname):
173
329
                # it's an option
174
 
                opts.append('--%s' % name)
 
330
                opts.append('--%s' % optname)
175
331
                if value is not None and value is not True:
176
332
                    opts.append(str(value))
177
333
            else:
221
377
    directory is shown.  Otherwise, only the status of the specified
222
378
    files or directories is reported.  If a directory is given, status
223
379
    is reported for everything inside that directory.
 
380
 
 
381
    If a revision is specified, the changes since that revision are shown.
224
382
    """
225
383
    takes_args = ['file*']
226
 
    takes_options = ['all', 'show-ids']
 
384
    takes_options = ['all', 'show-ids', 'revision']
227
385
    aliases = ['st', 'stat']
228
386
    
229
387
    def run(self, all=False, show_ids=False, file_list=None):
230
388
        if file_list:
231
 
            b = Branch(file_list[0], lock_mode='r')
 
389
            b = find_branch(file_list[0])
232
390
            file_list = [b.relpath(x) for x in file_list]
233
391
            # special case: only one path was given and it's the root
234
392
            # of the branch
235
393
            if file_list == ['']:
236
394
                file_list = None
237
395
        else:
238
 
            b = Branch('.', lock_mode='r')
239
 
        import status
240
 
        status.show_status(b, show_unchanged=all, show_ids=show_ids,
241
 
                           specific_files=file_list)
 
396
            b = find_branch('.')
 
397
            
 
398
        from bzrlib.status import show_status
 
399
        show_status(b, show_unchanged=all, show_ids=show_ids,
 
400
                    specific_files=file_list)
242
401
 
243
402
 
244
403
class cmd_cat_revision(Command):
248
407
    takes_args = ['revision_id']
249
408
    
250
409
    def run(self, revision_id):
251
 
        Branch('.').get_revision(revision_id).write_xml(sys.stdout)
 
410
        from bzrlib.xml import pack_xml
 
411
        pack_xml(find_branch('.').get_revision(revision_id), sys.stdout)
252
412
 
253
413
 
254
414
class cmd_revno(Command):
256
416
 
257
417
    This is equal to the number of revisions on this branch."""
258
418
    def run(self):
259
 
        print Branch('.').revno()
 
419
        print find_branch('.').revno()
 
420
 
 
421
class cmd_revision_info(Command):
 
422
    """Show revision number and revision id for a given revision identifier.
 
423
    """
 
424
    hidden = True
 
425
    takes_args = ['revision_info*']
 
426
    takes_options = ['revision']
 
427
    def run(self, revision=None, revision_info_list=None):
 
428
        from bzrlib.branch import find_branch
 
429
 
 
430
        revs = []
 
431
        if revision is not None:
 
432
            revs.extend(revision)
 
433
        if revision_info_list is not None:
 
434
            revs.extend(revision_info_list)
 
435
        if len(revs) == 0:
 
436
            raise BzrCommandError('You must supply a revision identifier')
 
437
 
 
438
        b = find_branch('.')
 
439
 
 
440
        for rev in revs:
 
441
            print '%4d %s' % b.get_revision_info(rev)
260
442
 
261
443
    
262
444
class cmd_add(Command):
272
454
    whether already versioned or not, are searched for files or
273
455
    subdirectories that are neither versioned or ignored, and these
274
456
    are added.  This search proceeds recursively into versioned
275
 
    directories.
 
457
    directories.  If no names are given '.' is assumed.
276
458
 
277
 
    Therefore simply saying 'bzr add .' will version all files that
 
459
    Therefore simply saying 'bzr add' will version all files that
278
460
    are currently unknown.
279
461
 
280
462
    TODO: Perhaps adding a file whose directly is not versioned should
281
463
    recursively add that parent, rather than giving an error?
282
464
    """
283
 
    takes_args = ['file+']
284
 
    takes_options = ['verbose']
 
465
    takes_args = ['file*']
 
466
    takes_options = ['verbose', 'no-recurse']
285
467
    
286
 
    def run(self, file_list, verbose=False):
287
 
        bzrlib.add.smart_add(file_list, verbose)
 
468
    def run(self, file_list, verbose=False, no_recurse=False):
 
469
        from bzrlib.add import smart_add
 
470
        smart_add(file_list, verbose, not no_recurse)
 
471
 
 
472
 
 
473
 
 
474
class cmd_mkdir(Command):
 
475
    """Create a new versioned directory.
 
476
 
 
477
    This is equivalent to creating the directory and then adding it.
 
478
    """
 
479
    takes_args = ['dir+']
 
480
 
 
481
    def run(self, dir_list):
 
482
        b = None
 
483
        
 
484
        for d in dir_list:
 
485
            os.mkdir(d)
 
486
            if not b:
 
487
                b = find_branch(d)
 
488
            b.add([d], verbose=True)
288
489
 
289
490
 
290
491
class cmd_relpath(Command):
291
492
    """Show path of a file relative to root"""
292
493
    takes_args = ['filename']
 
494
    hidden = True
293
495
    
294
496
    def run(self, filename):
295
 
        print Branch(filename).relpath(filename)
 
497
        print find_branch(filename).relpath(filename)
296
498
 
297
499
 
298
500
 
299
501
class cmd_inventory(Command):
300
502
    """Show inventory of the current working copy or a revision."""
301
 
    takes_options = ['revision']
 
503
    takes_options = ['revision', 'show-ids']
302
504
    
303
 
    def run(self, revision=None):
304
 
        b = Branch('.')
 
505
    def run(self, revision=None, show_ids=False):
 
506
        b = find_branch('.')
305
507
        if revision == None:
306
508
            inv = b.read_working_inventory()
307
509
        else:
308
 
            inv = b.get_revision_inventory(b.lookup_revision(revision))
 
510
            if len(revision) > 1:
 
511
                raise BzrCommandError('bzr inventory --revision takes'
 
512
                    ' exactly one revision identifier')
 
513
            inv = b.get_revision_inventory(b.lookup_revision(revision[0]))
309
514
 
310
 
        for path, entry in inv.iter_entries():
311
 
            print '%-50s %s' % (entry.file_id, path)
 
515
        for path, entry in inv.entries():
 
516
            if show_ids:
 
517
                print '%-50s %s' % (path, entry.file_id)
 
518
            else:
 
519
                print path
312
520
 
313
521
 
314
522
class cmd_move(Command):
321
529
    """
322
530
    takes_args = ['source$', 'dest']
323
531
    def run(self, source_list, dest):
324
 
        b = Branch('.')
 
532
        b = find_branch('.')
325
533
 
 
534
        # TODO: glob expansion on windows?
326
535
        b.move([b.relpath(s) for s in source_list], b.relpath(dest))
327
536
 
328
537
 
343
552
    takes_args = ['from_name', 'to_name']
344
553
    
345
554
    def run(self, from_name, to_name):
346
 
        b = Branch('.')
 
555
        b = find_branch('.')
347
556
        b.rename_one(b.relpath(from_name), b.relpath(to_name))
348
557
 
349
558
 
350
559
 
 
560
class cmd_mv(Command):
 
561
    """Move or rename a file.
 
562
 
 
563
    usage:
 
564
        bzr mv OLDNAME NEWNAME
 
565
        bzr mv SOURCE... DESTINATION
 
566
 
 
567
    If the last argument is a versioned directory, all the other names
 
568
    are moved into it.  Otherwise, there must be exactly two arguments
 
569
    and the file is changed to a new name, which must not already exist.
 
570
 
 
571
    Files cannot be moved between branches.
 
572
    """
 
573
    takes_args = ['names*']
 
574
    def run(self, names_list):
 
575
        if len(names_list) < 2:
 
576
            raise BzrCommandError("missing file argument")
 
577
        b = find_branch(names_list[0])
 
578
 
 
579
        rel_names = [b.relpath(x) for x in names_list]
 
580
        
 
581
        if os.path.isdir(names_list[-1]):
 
582
            # move into existing directory
 
583
            b.move(rel_names[:-1], rel_names[-1])
 
584
        else:
 
585
            if len(names_list) != 2:
 
586
                raise BzrCommandError('to mv multiple files the destination '
 
587
                                      'must be a versioned directory')
 
588
            b.move(rel_names[0], rel_names[1])
 
589
            
 
590
    
 
591
 
 
592
 
 
593
class cmd_pull(Command):
 
594
    """Pull any changes from another branch into the current one.
 
595
 
 
596
    If the location is omitted, the last-used location will be used.
 
597
    Both the revision history and the working directory will be
 
598
    updated.
 
599
 
 
600
    This command only works on branches that have not diverged.  Branches are
 
601
    considered diverged if both branches have had commits without first
 
602
    pulling from the other.
 
603
 
 
604
    If branches have diverged, you can use 'bzr merge' to pull the text changes
 
605
    from one into the other.
 
606
    """
 
607
    takes_args = ['location?']
 
608
 
 
609
    def run(self, location=None):
 
610
        from bzrlib.merge import merge
 
611
        import tempfile
 
612
        from shutil import rmtree
 
613
        import errno
 
614
        
 
615
        br_to = find_branch('.')
 
616
        stored_loc = None
 
617
        try:
 
618
            stored_loc = br_to.controlfile("x-pull", "rb").read().rstrip('\n')
 
619
        except IOError, e:
 
620
            if e.errno != errno.ENOENT:
 
621
                raise
 
622
        if location is None:
 
623
            if stored_loc is None:
 
624
                raise BzrCommandError("No pull location known or specified.")
 
625
            else:
 
626
                print "Using last location: %s" % stored_loc
 
627
                location = stored_loc
 
628
        cache_root = tempfile.mkdtemp()
 
629
        from bzrlib.branch import DivergedBranches
 
630
        br_from = find_branch(location)
 
631
        location = pull_loc(br_from)
 
632
        old_revno = br_to.revno()
 
633
        try:
 
634
            from branch import find_cached_branch, DivergedBranches
 
635
            br_from = find_cached_branch(location, cache_root)
 
636
            location = pull_loc(br_from)
 
637
            old_revno = br_to.revno()
 
638
            try:
 
639
                br_to.update_revisions(br_from)
 
640
            except DivergedBranches:
 
641
                raise BzrCommandError("These branches have diverged."
 
642
                    "  Try merge.")
 
643
                
 
644
            merge(('.', -1), ('.', old_revno), check_clean=False)
 
645
            if location != stored_loc:
 
646
                br_to.controlfile("x-pull", "wb").write(location + "\n")
 
647
        finally:
 
648
            rmtree(cache_root)
 
649
 
 
650
 
 
651
 
 
652
class cmd_branch(Command):
 
653
    """Create a new copy of a branch.
 
654
 
 
655
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
 
656
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
 
657
 
 
658
    To retrieve the branch as of a particular revision, supply the --revision
 
659
    parameter, as in "branch foo/bar -r 5".
 
660
    """
 
661
    takes_args = ['from_location', 'to_location?']
 
662
    takes_options = ['revision']
 
663
    aliases = ['get', 'clone']
 
664
 
 
665
    def run(self, from_location, to_location=None, revision=None):
 
666
        import errno
 
667
        from bzrlib.merge import merge
 
668
        from bzrlib.branch import DivergedBranches, \
 
669
             find_cached_branch, Branch
 
670
        from shutil import rmtree
 
671
        from meta_store import CachedStore
 
672
        import tempfile
 
673
        cache_root = tempfile.mkdtemp()
 
674
 
 
675
        if revision is None:
 
676
            revision = [None]
 
677
        elif len(revision) > 1:
 
678
            raise BzrCommandError('bzr branch --revision takes exactly 1 revision value')
 
679
 
 
680
        try:
 
681
            try:
 
682
                br_from = find_cached_branch(from_location, cache_root)
 
683
            except OSError, e:
 
684
                if e.errno == errno.ENOENT:
 
685
                    raise BzrCommandError('Source location "%s" does not'
 
686
                                          ' exist.' % to_location)
 
687
                else:
 
688
                    raise
 
689
 
 
690
            if to_location is None:
 
691
                to_location = os.path.basename(from_location.rstrip("/\\"))
 
692
 
 
693
            try:
 
694
                os.mkdir(to_location)
 
695
            except OSError, e:
 
696
                if e.errno == errno.EEXIST:
 
697
                    raise BzrCommandError('Target directory "%s" already'
 
698
                                          ' exists.' % to_location)
 
699
                if e.errno == errno.ENOENT:
 
700
                    raise BzrCommandError('Parent of "%s" does not exist.' %
 
701
                                          to_location)
 
702
                else:
 
703
                    raise
 
704
            br_to = Branch(to_location, init=True)
 
705
 
 
706
            br_to.set_root_id(br_from.get_root_id())
 
707
 
 
708
            if revision:
 
709
                if revision[0] is None:
 
710
                    revno = br_from.revno()
 
711
                else:
 
712
                    revno, rev_id = br_from.get_revision_info(revision[0])
 
713
                try:
 
714
                    br_to.update_revisions(br_from, stop_revision=revno)
 
715
                except bzrlib.errors.NoSuchRevision:
 
716
                    rmtree(to_location)
 
717
                    msg = "The branch %s has no revision %d." % (from_location,
 
718
                                                                 revno)
 
719
                    raise BzrCommandError(msg)
 
720
            
 
721
            merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
722
                  check_clean=False, ignore_zero=True)
 
723
            from_location = pull_loc(br_from)
 
724
            br_to.controlfile("x-pull", "wb").write(from_location + "\n")
 
725
        finally:
 
726
            rmtree(cache_root)
 
727
 
 
728
 
 
729
def pull_loc(branch):
 
730
    # TODO: Should perhaps just make attribute be 'base' in
 
731
    # RemoteBranch and Branch?
 
732
    if hasattr(branch, "baseurl"):
 
733
        return branch.baseurl
 
734
    else:
 
735
        return branch.base
 
736
 
 
737
 
 
738
 
351
739
class cmd_renames(Command):
352
740
    """Show list of renamed files.
353
741
 
358
746
    takes_args = ['dir?']
359
747
 
360
748
    def run(self, dir='.'):
361
 
        b = Branch(dir)
 
749
        b = find_branch(dir)
362
750
        old_inv = b.basis_tree().inventory
363
751
        new_inv = b.read_working_inventory()
364
752
 
375
763
    def run(self, branch=None):
376
764
        import info
377
765
 
378
 
        from branch import find_branch
379
766
        b = find_branch(branch)
380
767
        info.show_info(b)
381
768
 
390
777
    takes_options = ['verbose']
391
778
    
392
779
    def run(self, file_list, verbose=False):
393
 
        b = Branch(file_list[0])
 
780
        b = find_branch(file_list[0])
394
781
        b.remove([b.relpath(f) for f in file_list], verbose=verbose)
395
782
 
396
783
 
404
791
    hidden = True
405
792
    takes_args = ['filename']
406
793
    def run(self, filename):
407
 
        b = Branch(filename)
 
794
        b = find_branch(filename)
408
795
        i = b.inventory.path2id(b.relpath(filename))
409
796
        if i == None:
410
 
            bailout("%r is not a versioned file" % filename)
 
797
            raise BzrError("%r is not a versioned file" % filename)
411
798
        else:
412
799
            print i
413
800
 
420
807
    hidden = True
421
808
    takes_args = ['filename']
422
809
    def run(self, filename):
423
 
        b = Branch(filename)
 
810
        b = find_branch(filename)
424
811
        inv = b.inventory
425
812
        fid = inv.path2id(b.relpath(filename))
426
813
        if fid == None:
427
 
            bailout("%r is not a versioned file" % filename)
 
814
            raise BzrError("%r is not a versioned file" % filename)
428
815
        for fip in inv.get_idpath(fid):
429
816
            print fip
430
817
 
431
818
 
432
819
class cmd_revision_history(Command):
433
820
    """Display list of revision ids on this branch."""
 
821
    hidden = True
434
822
    def run(self):
435
 
        for patchid in Branch('.').revision_history():
 
823
        for patchid in find_branch('.').revision_history():
436
824
            print patchid
437
825
 
438
826
 
439
827
class cmd_directories(Command):
440
828
    """Display list of versioned directories in this branch."""
441
829
    def run(self):
442
 
        for name, ie in Branch('.').read_working_inventory().directories():
 
830
        for name, ie in find_branch('.').read_working_inventory().directories():
443
831
            if name == '':
444
832
                print '.'
445
833
            else:
460
848
        bzr commit -m 'imported project'
461
849
    """
462
850
    def run(self):
 
851
        from bzrlib.branch import Branch
463
852
        Branch('.', init=True)
464
853
 
465
854
 
469
858
    If files are listed, only the changes in those files are listed.
470
859
    Otherwise, all changes for the tree are listed.
471
860
 
472
 
    TODO: Given two revision arguments, show the difference between them.
473
 
 
474
861
    TODO: Allow diff across branches.
475
862
 
476
863
    TODO: Option to use external diff command; could be GNU diff, wdiff,
485
872
          deleted files.
486
873
 
487
874
    TODO: This probably handles non-Unix newlines poorly.
 
875
 
 
876
    examples:
 
877
        bzr diff
 
878
        bzr diff -r1
 
879
        bzr diff -r1:2
488
880
    """
489
881
    
490
882
    takes_args = ['file*']
491
 
    takes_options = ['revision']
492
 
    aliases = ['di']
 
883
    takes_options = ['revision', 'diff-options']
 
884
    aliases = ['di', 'dif']
493
885
 
494
 
    def run(self, revision=None, file_list=None):
 
886
    def run(self, revision=None, file_list=None, diff_options=None):
495
887
        from bzrlib.diff import show_diff
496
 
    
497
 
        show_diff(Branch('.'), revision, specific_files=file_list)
498
 
 
 
888
 
 
889
        if file_list:
 
890
            b = find_branch(file_list[0])
 
891
            file_list = [b.relpath(f) for f in file_list]
 
892
            if file_list == ['']:
 
893
                # just pointing to top-of-tree
 
894
                file_list = None
 
895
        else:
 
896
            b = find_branch('.')
 
897
 
 
898
        if revision is not None:
 
899
            if len(revision) == 1:
 
900
                show_diff(b, revision[0], specific_files=file_list,
 
901
                          external_diff_options=diff_options)
 
902
            elif len(revision) == 2:
 
903
                show_diff(b, revision[0], specific_files=file_list,
 
904
                          external_diff_options=diff_options,
 
905
                          revision2=revision[1])
 
906
            else:
 
907
                raise BzrCommandError('bzr diff --revision takes exactly one or two revision identifiers')
 
908
        else:
 
909
            show_diff(b, None, specific_files=file_list,
 
910
                      external_diff_options=diff_options)
499
911
 
500
912
        
501
913
 
506
918
    TODO: Show files deleted since a previous revision, or between two revisions.
507
919
    """
508
920
    def run(self, show_ids=False):
509
 
        b = Branch('.')
 
921
        b = find_branch('.')
510
922
        old = b.basis_tree()
511
923
        new = b.working_tree()
512
924
 
527
939
    """List files modified in working tree."""
528
940
    hidden = True
529
941
    def run(self):
530
 
        import statcache
531
 
        b = Branch('.')
532
 
        inv = b.read_working_inventory()
533
 
        sc = statcache.update_cache(b, inv)
534
 
        basis = b.basis_tree()
535
 
        basis_inv = basis.inventory
536
 
        
537
 
        # We used to do this through iter_entries(), but that's slow
538
 
        # when most of the files are unmodified, as is usually the
539
 
        # case.  So instead we iterate by inventory entry, and only
540
 
        # calculate paths as necessary.
541
 
 
542
 
        for file_id in basis_inv:
543
 
            cacheentry = sc.get(file_id)
544
 
            if not cacheentry:                 # deleted
545
 
                continue
546
 
            ie = basis_inv[file_id]
547
 
            if cacheentry[statcache.SC_SHA1] != ie.text_sha1:
548
 
                path = inv.id2path(file_id)
549
 
                print path
 
942
        from bzrlib.delta import compare_trees
 
943
 
 
944
        b = find_branch('.')
 
945
        td = compare_trees(b.basis_tree(), b.working_tree())
 
946
 
 
947
        for path, id, kind in td.modified:
 
948
            print path
550
949
 
551
950
 
552
951
 
554
953
    """List files added in working tree."""
555
954
    hidden = True
556
955
    def run(self):
557
 
        b = Branch('.')
 
956
        b = find_branch('.')
558
957
        wt = b.working_tree()
559
958
        basis_inv = b.basis_tree().inventory
560
959
        inv = wt.inventory
576
975
    takes_args = ['filename?']
577
976
    def run(self, filename=None):
578
977
        """Print the branch root."""
579
 
        from branch import find_branch
580
978
        b = find_branch(filename)
581
979
        print getattr(b, 'base', None) or getattr(b, 'baseurl')
582
980
 
584
982
class cmd_log(Command):
585
983
    """Show log of this branch.
586
984
 
587
 
    TODO: Option to limit range.
588
 
 
589
 
    TODO: Perhaps show most-recent first with an option for last.
 
985
    To request a range of logs, you can use the command -r begin:end
 
986
    -r revision requests a specific revision, -r :end or -r begin: are
 
987
    also valid.
 
988
 
 
989
    --message allows you to give a regular expression, which will be evaluated
 
990
    so that only matching entries will be displayed.
 
991
 
 
992
    TODO: Make --revision support uuid: and hash: [future tag:] notation.
 
993
  
590
994
    """
 
995
 
591
996
    takes_args = ['filename?']
592
 
    takes_options = ['timezone', 'verbose', 'show-ids']
593
 
    def run(self, filename=None, timezone='original', verbose=False, show_ids=False):
594
 
        from branch import find_branch
595
 
        b = find_branch((filename or '.'), lock_mode='r')
 
997
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision',
 
998
                     'long', 'message', 'short',]
 
999
    
 
1000
    def run(self, filename=None, timezone='original',
 
1001
            verbose=False,
 
1002
            show_ids=False,
 
1003
            forward=False,
 
1004
            revision=None,
 
1005
            message=None,
 
1006
            long=False,
 
1007
            short=False):
 
1008
        from bzrlib.branch import find_branch
 
1009
        from bzrlib.log import log_formatter, show_log
 
1010
        import codecs
 
1011
 
 
1012
        direction = (forward and 'forward') or 'reverse'
 
1013
        
596
1014
        if filename:
597
 
            filename = b.relpath(filename)
598
 
        bzrlib.show_log(b, filename,
599
 
                        show_timezone=timezone,
600
 
                        verbose=verbose,
601
 
                        show_ids=show_ids)
 
1015
            b = find_branch(filename)
 
1016
            fp = b.relpath(filename)
 
1017
            if fp:
 
1018
                file_id = b.read_working_inventory().path2id(fp)
 
1019
            else:
 
1020
                file_id = None  # points to branch root
 
1021
        else:
 
1022
            b = find_branch('.')
 
1023
            file_id = None
 
1024
 
 
1025
        if revision is None:
 
1026
            rev1 = None
 
1027
            rev2 = None
 
1028
        elif len(revision) == 1:
 
1029
            rev1 = rev2 = b.get_revision_info(revision[0])[0]
 
1030
        elif len(revision) == 2:
 
1031
            rev1 = b.get_revision_info(revision[0])[0]
 
1032
            rev2 = b.get_revision_info(revision[1])[0]
 
1033
        else:
 
1034
            raise BzrCommandError('bzr log --revision takes one or two values.')
 
1035
 
 
1036
        if rev1 == 0:
 
1037
            rev1 = None
 
1038
        if rev2 == 0:
 
1039
            rev2 = None
 
1040
 
 
1041
        mutter('encoding log as %r' % bzrlib.user_encoding)
 
1042
 
 
1043
        # use 'replace' so that we don't abort if trying to write out
 
1044
        # in e.g. the default C locale.
 
1045
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
 
1046
 
 
1047
        if not short:
 
1048
            log_format = 'long'
 
1049
        else:
 
1050
            log_format = 'short'
 
1051
        lf = log_formatter(log_format,
 
1052
                           show_ids=show_ids,
 
1053
                           to_file=outf,
 
1054
                           show_timezone=timezone)
 
1055
 
 
1056
        show_log(b,
 
1057
                 lf,
 
1058
                 file_id,
 
1059
                 verbose=verbose,
 
1060
                 direction=direction,
 
1061
                 start_revision=rev1,
 
1062
                 end_revision=rev2,
 
1063
                 search=message)
602
1064
 
603
1065
 
604
1066
 
605
1067
class cmd_touching_revisions(Command):
606
 
    """Return revision-ids which affected a particular file."""
 
1068
    """Return revision-ids which affected a particular file.
 
1069
 
 
1070
    A more user-friendly interface is "bzr log FILE"."""
607
1071
    hidden = True
608
1072
    takes_args = ["filename"]
609
1073
    def run(self, filename):
610
 
        b = Branch(filename, lock_mode='r')
 
1074
        b = find_branch(filename)
611
1075
        inv = b.read_working_inventory()
612
1076
        file_id = inv.path2id(b.relpath(filename))
613
1077
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
621
1085
    """
622
1086
    hidden = True
623
1087
    def run(self, revision=None, verbose=False):
624
 
        b = Branch('.')
 
1088
        b = find_branch('.')
625
1089
        if revision == None:
626
1090
            tree = b.working_tree()
627
1091
        else:
643
1107
 
644
1108
 
645
1109
class cmd_unknowns(Command):
646
 
    """List unknown files"""
 
1110
    """List unknown files."""
647
1111
    def run(self):
648
 
        for f in Branch('.').unknowns():
 
1112
        from bzrlib.osutils import quotefn
 
1113
        for f in find_branch('.').unknowns():
649
1114
            print quotefn(f)
650
1115
 
651
1116
 
652
1117
 
653
1118
class cmd_ignore(Command):
654
 
    """Ignore a command or pattern
 
1119
    """Ignore a command or pattern.
655
1120
 
656
1121
    To remove patterns from the ignore list, edit the .bzrignore file.
657
1122
 
671
1136
    
672
1137
    def run(self, name_pattern):
673
1138
        from bzrlib.atomicfile import AtomicFile
674
 
        import codecs
 
1139
        import os.path
675
1140
 
676
 
        b = Branch('.')
 
1141
        b = find_branch('.')
677
1142
        ifn = b.abspath('.bzrignore')
678
1143
 
679
 
        # FIXME: probably doesn't handle non-ascii patterns
680
 
 
681
1144
        if os.path.exists(ifn):
682
 
            f = b.controlfile(ifn, 'rt')
683
 
            igns = f.read()
684
 
            f.close()
 
1145
            f = open(ifn, 'rt')
 
1146
            try:
 
1147
                igns = f.read().decode('utf-8')
 
1148
            finally:
 
1149
                f.close()
685
1150
        else:
686
1151
            igns = ''
687
1152
 
 
1153
        # TODO: If the file already uses crlf-style termination, maybe
 
1154
        # we should use that for the newly added lines?
 
1155
 
688
1156
        if igns and igns[-1] != '\n':
689
1157
            igns += '\n'
690
1158
        igns += name_pattern + '\n'
691
1159
 
692
 
        f = AtomicFile(ifn, 'wt')
693
 
        f.write(igns)
694
 
        f.commit()
 
1160
        try:
 
1161
            f = AtomicFile(ifn, 'wt')
 
1162
            f.write(igns.encode('utf-8'))
 
1163
            f.commit()
 
1164
        finally:
 
1165
            f.close()
695
1166
 
696
1167
        inv = b.working_tree().inventory
697
1168
        if inv.path2id('.bzrignore'):
707
1178
 
708
1179
    See also: bzr ignore"""
709
1180
    def run(self):
710
 
        tree = Branch('.').working_tree()
 
1181
        tree = find_branch('.').working_tree()
711
1182
        for path, file_class, kind, file_id in tree.list_files():
712
1183
            if file_class != 'I':
713
1184
                continue
731
1202
        except ValueError:
732
1203
            raise BzrCommandError("not a valid revision-number: %r" % revno)
733
1204
 
734
 
        print Branch('.').lookup_revision(revno)
 
1205
        print find_branch('.').lookup_revision(revno)
735
1206
 
736
1207
 
737
1208
class cmd_export(Command):
738
1209
    """Export past revision to destination directory.
739
1210
 
740
 
    If no revision is specified this exports the last committed revision."""
 
1211
    If no revision is specified this exports the last committed revision.
 
1212
 
 
1213
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
 
1214
    given, try to find the format with the extension. If no extension
 
1215
    is found exports to a directory (equivalent to --format=dir).
 
1216
 
 
1217
    Root may be the top directory for tar, tgz and tbz2 formats. If none
 
1218
    is given, the top directory will be the root name of the file."""
 
1219
    # TODO: list known exporters
741
1220
    takes_args = ['dest']
742
 
    takes_options = ['revision']
743
 
    def run(self, dest, revision=None):
744
 
        b = Branch('.')
745
 
        if revision == None:
746
 
            rh = b.revision_history()[-1]
 
1221
    takes_options = ['revision', 'format', 'root']
 
1222
    def run(self, dest, revision=None, format=None, root=None):
 
1223
        import os.path
 
1224
        b = find_branch('.')
 
1225
        if revision is None:
 
1226
            rev_id = b.last_patch()
747
1227
        else:
748
 
            rh = b.lookup_revision(int(revision))
749
 
        t = b.revision_tree(rh)
750
 
        t.export(dest)
 
1228
            if len(revision) != 1:
 
1229
                raise BzrError('bzr export --revision takes exactly 1 argument')
 
1230
            revno, rev_id = b.get_revision_info(revision[0])
 
1231
        t = b.revision_tree(rev_id)
 
1232
        root, ext = os.path.splitext(dest)
 
1233
        if not format:
 
1234
            if ext in (".tar",):
 
1235
                format = "tar"
 
1236
            elif ext in (".gz", ".tgz"):
 
1237
                format = "tgz"
 
1238
            elif ext in (".bz2", ".tbz2"):
 
1239
                format = "tbz2"
 
1240
            else:
 
1241
                format = "dir"
 
1242
        t.export(dest, format, root)
751
1243
 
752
1244
 
753
1245
class cmd_cat(Command):
759
1251
    def run(self, filename, revision=None):
760
1252
        if revision == None:
761
1253
            raise BzrCommandError("bzr cat requires a revision number")
762
 
        b = Branch('.')
763
 
        b.print_file(b.relpath(filename), int(revision))
 
1254
        elif len(revision) != 1:
 
1255
            raise BzrCommandError("bzr cat --revision takes exactly one number")
 
1256
        b = find_branch('.')
 
1257
        b.print_file(b.relpath(filename), revision[0])
764
1258
 
765
1259
 
766
1260
class cmd_local_time_offset(Command):
773
1267
 
774
1268
class cmd_commit(Command):
775
1269
    """Commit changes into a new revision.
776
 
 
777
 
    TODO: Commit only selected files.
 
1270
    
 
1271
    If no arguments are given, the entire tree is committed.
 
1272
 
 
1273
    If selected files are specified, only changes to those files are
 
1274
    committed.  If a directory is specified then the directory and everything 
 
1275
    within it is committed.
 
1276
 
 
1277
    A selected-file commit may fail in some cases where the committed
 
1278
    tree would be invalid, such as trying to commit a file in a
 
1279
    newly-added directory that is not itself committed.
778
1280
 
779
1281
    TODO: Run hooks on tree to-be-committed, and after commit.
780
1282
 
781
1283
    TODO: Strict commit that fails if there are unknown or deleted files.
782
1284
    """
783
 
    takes_options = ['message', 'file', 'verbose']
 
1285
    takes_args = ['selected*']
 
1286
    takes_options = ['message', 'file', 'verbose', 'unchanged']
784
1287
    aliases = ['ci', 'checkin']
785
1288
 
786
 
    def run(self, message=None, file=None, verbose=False):
 
1289
    # TODO: Give better message for -s, --summary, used by tla people
 
1290
    
 
1291
    def run(self, message=None, file=None, verbose=True, selected_list=None,
 
1292
            unchanged=False):
 
1293
        from bzrlib.errors import PointlessCommit
 
1294
        from bzrlib.osutils import get_text_message
 
1295
 
787
1296
        ## Warning: shadows builtin file()
788
1297
        if not message and not file:
789
 
            raise BzrCommandError("please specify a commit message",
790
 
                                  ["use either --message or --file"])
 
1298
            # FIXME: Ugly; change status code to send to a provided function?
 
1299
            
 
1300
            import cStringIO
 
1301
            stdout = sys.stdout
 
1302
            catcher = cStringIO.StringIO()
 
1303
            sys.stdout = catcher
 
1304
            cmd_status({"file_list":selected_list}, {})
 
1305
            info = catcher.getvalue()
 
1306
            sys.stdout = stdout
 
1307
            message = get_text_message(info)
 
1308
            
 
1309
            if message is None:
 
1310
                raise BzrCommandError("please specify a commit message",
 
1311
                                      ["use either --message or --file"])
791
1312
        elif message and file:
792
1313
            raise BzrCommandError("please specify either --message or --file")
793
1314
        
795
1316
            import codecs
796
1317
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
797
1318
 
798
 
        Branch('.').commit(message, verbose=verbose)
 
1319
        b = find_branch('.')
 
1320
        if selected_list:
 
1321
            selected_list = [b.relpath(s) for s in selected_list]
 
1322
            
 
1323
        try:
 
1324
            b.commit(message, verbose=verbose,
 
1325
                     specific_files=selected_list,
 
1326
                     allow_pointless=unchanged)
 
1327
        except PointlessCommit:
 
1328
            # FIXME: This should really happen before the file is read in;
 
1329
            # perhaps prepare the commit; get the message; then actually commit
 
1330
            raise BzrCommandError("no changes to commit",
 
1331
                                  ["use --unchanged to commit anyhow"])
799
1332
 
800
1333
 
801
1334
class cmd_check(Command):
803
1336
 
804
1337
    This command checks various invariants about the branch storage to
805
1338
    detect data corruption or bzr bugs.
806
 
    """
807
 
    takes_args = ['dir?']
808
 
    def run(self, dir='.'):
809
 
        import bzrlib.check
810
 
        bzrlib.check.check(Branch(dir, find_root=False))
 
1339
 
 
1340
    If given the --update flag, it will update some optional fields
 
1341
    to help ensure data consistency.
 
1342
    """
 
1343
    takes_args = ['dir?']
 
1344
 
 
1345
    def run(self, dir='.'):
 
1346
        from bzrlib.check import check
 
1347
        check(find_branch(dir))
 
1348
 
 
1349
 
 
1350
 
 
1351
class cmd_scan_cache(Command):
 
1352
    hidden = True
 
1353
    def run(self):
 
1354
        from bzrlib.hashcache import HashCache
 
1355
        import os
 
1356
 
 
1357
        c = HashCache('.')
 
1358
        c.read()
 
1359
        c.scan()
 
1360
            
 
1361
        print '%6d stats' % c.stat_count
 
1362
        print '%6d in hashcache' % len(c._cache)
 
1363
        print '%6d files removed from cache' % c.removed_count
 
1364
        print '%6d hashes updated' % c.update_count
 
1365
        print '%6d files changed too recently to cache' % c.danger_count
 
1366
 
 
1367
        if c.needs_write:
 
1368
            c.write()
 
1369
            
 
1370
 
 
1371
 
 
1372
class cmd_upgrade(Command):
 
1373
    """Upgrade branch storage to current format.
 
1374
 
 
1375
    This should normally be used only after the check command tells
 
1376
    you to run it.
 
1377
    """
 
1378
    takes_args = ['dir?']
 
1379
 
 
1380
    def run(self, dir='.'):
 
1381
        from bzrlib.upgrade import upgrade
 
1382
        upgrade(find_branch(dir))
811
1383
 
812
1384
 
813
1385
 
816
1388
    takes_options = ['email']
817
1389
    
818
1390
    def run(self, email=False):
 
1391
        try:
 
1392
            b = bzrlib.branch.find_branch('.')
 
1393
        except:
 
1394
            b = None
 
1395
        
819
1396
        if email:
820
 
            print bzrlib.osutils.user_email()
 
1397
            print bzrlib.osutils.user_email(b)
821
1398
        else:
822
 
            print bzrlib.osutils.username()
 
1399
            print bzrlib.osutils.username(b)
823
1400
 
824
1401
 
825
1402
class cmd_selftest(Command):
826
1403
    """Run internal test suite"""
827
1404
    hidden = True
828
 
    def run(self):
829
 
        failures, tests = 0, 0
830
 
 
831
 
        import doctest, bzrlib.store, bzrlib.tests
832
 
        bzrlib.trace.verbose = False
833
 
 
834
 
        for m in bzrlib.store, bzrlib.inventory, bzrlib.branch, bzrlib.osutils, \
835
 
            bzrlib.tree, bzrlib.tests, bzrlib.commands, bzrlib.add:
836
 
            mf, mt = doctest.testmod(m)
837
 
            failures += mf
838
 
            tests += mt
839
 
            print '%-40s %3d tests' % (m.__name__, mt),
840
 
            if mf:
841
 
                print '%3d FAILED!' % mf
842
 
            else:
843
 
                print
844
 
 
845
 
        print '%-40s %3d tests' % ('total', tests),
846
 
        if failures:
847
 
            print '%3d FAILED!' % failures
848
 
        else:
849
 
            print
850
 
 
 
1405
    takes_options = ['verbose']
 
1406
    def run(self, verbose=False):
 
1407
        from bzrlib.selftest import selftest
 
1408
        return int(not selftest(verbose=verbose))
851
1409
 
852
1410
 
853
1411
class cmd_version(Command):
854
 
    """Show version of bzr"""
 
1412
    """Show version of bzr."""
855
1413
    def run(self):
856
1414
        show_version()
857
1415
 
858
1416
def show_version():
859
1417
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
 
1418
    # is bzrlib itself in a branch?
 
1419
    bzrrev = bzrlib.get_bzr_revision()
 
1420
    if bzrrev:
 
1421
        print "  (bzr checkout, revision %d {%s})" % bzrrev
860
1422
    print bzrlib.__copyright__
861
1423
    print "http://bazaar-ng.org/"
862
1424
    print
871
1433
    def run(self):
872
1434
        print "it sure does!"
873
1435
 
 
1436
def parse_spec(spec):
 
1437
    """
 
1438
    >>> parse_spec(None)
 
1439
    [None, None]
 
1440
    >>> parse_spec("./")
 
1441
    ['./', None]
 
1442
    >>> parse_spec("../@")
 
1443
    ['..', -1]
 
1444
    >>> parse_spec("../f/@35")
 
1445
    ['../f', 35]
 
1446
    >>> parse_spec('./@revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67')
 
1447
    ['.', 'revid:john@arbash-meinel.com-20050711044610-3ca0327c6a222f67']
 
1448
    """
 
1449
    if spec is None:
 
1450
        return [None, None]
 
1451
    if '/@' in spec:
 
1452
        parsed = spec.split('/@')
 
1453
        assert len(parsed) == 2
 
1454
        if parsed[1] == "":
 
1455
            parsed[1] = -1
 
1456
        else:
 
1457
            try:
 
1458
                parsed[1] = int(parsed[1])
 
1459
            except ValueError:
 
1460
                pass # We can allow stuff like ./@revid:blahblahblah
 
1461
            else:
 
1462
                assert parsed[1] >=0
 
1463
    else:
 
1464
        parsed = [spec, None]
 
1465
    return parsed
 
1466
 
 
1467
 
 
1468
 
 
1469
class cmd_merge(Command):
 
1470
    """Perform a three-way merge.
 
1471
    
 
1472
    The branch is the branch you will merge from.  By default, it will merge
 
1473
    the latest revision.  If you specify a revision, that revision will be
 
1474
    merged.  If you specify two revisions, the first will be used as a BASE, 
 
1475
    and the second one as OTHER.  Revision numbers are always relative to the
 
1476
    specified branch.
 
1477
    
 
1478
    Examples:
 
1479
 
 
1480
    To merge the latest revision from bzr.dev
 
1481
    bzr merge ../bzr.dev
 
1482
 
 
1483
    To merge changes up to and including revision 82 from bzr.dev
 
1484
    bzr merge -r 82 ../bzr.dev
 
1485
 
 
1486
    To merge the changes introduced by 82, without previous changes:
 
1487
    bzr merge -r 81..82 ../bzr.dev
 
1488
    
 
1489
    merge refuses to run if there are any uncommitted changes, unless
 
1490
    --force is given.
 
1491
    """
 
1492
    takes_args = ['branch?']
 
1493
    takes_options = ['revision', 'force', 'merge-type']
 
1494
 
 
1495
    def run(self, branch='.', revision=None, force=False, 
 
1496
            merge_type=None):
 
1497
        from bzrlib.merge import merge
 
1498
        from bzrlib.merge_core import ApplyMerge3
 
1499
        if merge_type is None:
 
1500
            merge_type = ApplyMerge3
 
1501
 
 
1502
        if revision is None or len(revision) < 1:
 
1503
            base = (None, None)
 
1504
            other = (branch, -1)
 
1505
        else:
 
1506
            if len(revision) == 1:
 
1507
                other = (branch, revision[0])
 
1508
                base = (None, None)
 
1509
            else:
 
1510
                assert len(revision) == 2
 
1511
                if None in revision:
 
1512
                    raise BzrCommandError(
 
1513
                        "Merge doesn't permit that revision specifier.")
 
1514
                base = (branch, revision[0])
 
1515
                other = (branch, revision[1])
 
1516
            
 
1517
        merge(other, base, check_clean=(not force), merge_type=merge_type)
 
1518
 
 
1519
 
 
1520
class cmd_revert(Command):
 
1521
    """Reverse all changes since the last commit.
 
1522
 
 
1523
    Only versioned files are affected.  Specify filenames to revert only 
 
1524
    those files.  By default, any files that are changed will be backed up
 
1525
    first.  Backup files have a '~' appended to their name.
 
1526
    """
 
1527
    takes_options = ['revision', 'no-backup']
 
1528
    takes_args = ['file*']
 
1529
    aliases = ['merge-revert']
 
1530
 
 
1531
    def run(self, revision=None, no_backup=False, file_list=None):
 
1532
        from bzrlib.merge import merge
 
1533
        if file_list is not None:
 
1534
            if len(file_list) == 0:
 
1535
                raise BzrCommandError("No files specified")
 
1536
        if revision is None:
 
1537
            revision = [-1]
 
1538
        elif len(revision) != 1:
 
1539
            raise BzrCommandError('bzr revert --revision takes exactly 1 argument')
 
1540
        merge(('.', revision[0]), parse_spec('.'),
 
1541
              check_clean=False,
 
1542
              ignore_zero=True,
 
1543
              backup_files=not no_backup,
 
1544
              file_list=file_list)
 
1545
 
874
1546
 
875
1547
class cmd_assert_fail(Command):
876
1548
    """Test reporting of assertion failures"""
891
1563
        help.help(topic)
892
1564
 
893
1565
 
894
 
class cmd_update_stat_cache(Command):
895
 
    """Update stat-cache mapping inodes to SHA-1 hashes.
896
 
 
897
 
    For testing only."""
 
1566
class cmd_shell_complete(Command):
 
1567
    """Show appropriate completions for context.
 
1568
 
 
1569
    For a list of all available commands, say 'bzr shell-complete'."""
 
1570
    takes_args = ['context?']
 
1571
    aliases = ['s-c']
 
1572
    hidden = True
 
1573
    
 
1574
    def run(self, context=None):
 
1575
        import shellcomplete
 
1576
        shellcomplete.shellcomplete(context)
 
1577
 
 
1578
 
 
1579
class cmd_missing(Command):
 
1580
    """What is missing in this branch relative to other branch.
 
1581
    """
 
1582
    takes_args = ['remote?']
 
1583
    aliases = ['mis', 'miss']
 
1584
    # We don't have to add quiet to the list, because 
 
1585
    # unknown options are parsed as booleans
 
1586
    takes_options = ['verbose', 'quiet']
 
1587
 
 
1588
    def run(self, remote=None, verbose=False, quiet=False):
 
1589
        from bzrlib.branch import find_branch, DivergedBranches
 
1590
        from bzrlib.errors import BzrCommandError
 
1591
        from bzrlib.missing import get_parent, show_missing
 
1592
 
 
1593
        if verbose and quiet:
 
1594
            raise BzrCommandError('Cannot pass both quiet and verbose')
 
1595
 
 
1596
        b = find_branch('.')
 
1597
        parent = get_parent(b)
 
1598
        if remote is None:
 
1599
            if parent is None:
 
1600
                raise BzrCommandError("No missing location known or specified.")
 
1601
            else:
 
1602
                if not quiet:
 
1603
                    print "Using last location: %s" % parent
 
1604
                remote = parent
 
1605
        elif parent is None:
 
1606
            # We only update x-pull if it did not exist, missing should not change the parent
 
1607
            b.controlfile('x-pull', 'wb').write(remote + '\n')
 
1608
        br_remote = find_branch(remote)
 
1609
 
 
1610
        return show_missing(b, br_remote, verbose=verbose, quiet=quiet)
 
1611
 
 
1612
 
 
1613
 
 
1614
class cmd_plugins(Command):
 
1615
    """List plugins"""
898
1616
    hidden = True
899
1617
    def run(self):
900
 
        import statcache
901
 
        b = Branch('.')
902
 
        statcache.update_cache(b.base, b.read_working_inventory())
903
 
 
904
 
 
905
 
######################################################################
906
 
# main routine
 
1618
        import bzrlib.plugin
 
1619
        from inspect import getdoc
 
1620
        from pprint import pprint
 
1621
        for plugin in bzrlib.plugin.all_plugins:
 
1622
            print plugin.__path__[0]
 
1623
            d = getdoc(plugin)
 
1624
            if d:
 
1625
                print '\t', d.split('\n')[0]
 
1626
 
 
1627
        #pprint(bzrlib.plugin.all_plugins)
 
1628
 
907
1629
 
908
1630
 
909
1631
# list of all available options; the rhs can be either None for an
911
1633
# the type.
912
1634
OPTIONS = {
913
1635
    'all':                    None,
 
1636
    'diff-options':           str,
914
1637
    'help':                   None,
915
1638
    'file':                   unicode,
 
1639
    'force':                  None,
 
1640
    'format':                 unicode,
 
1641
    'forward':                None,
916
1642
    'message':                unicode,
 
1643
    'no-recurse':             None,
917
1644
    'profile':                None,
918
 
    'revision':               int,
 
1645
    'revision':               _parse_revision_str,
 
1646
    'short':                  None,
919
1647
    'show-ids':               None,
920
1648
    'timezone':               str,
921
1649
    'verbose':                None,
922
1650
    'version':                None,
923
1651
    'email':                  None,
 
1652
    'unchanged':              None,
 
1653
    'update':                 None,
 
1654
    'long':                   None,
 
1655
    'root':                   str,
 
1656
    'no-backup':              None,
 
1657
    'merge-type':             get_merge_type,
924
1658
    }
925
1659
 
926
1660
SHORT_OPTIONS = {
 
1661
    'F':                      'file', 
 
1662
    'h':                      'help',
927
1663
    'm':                      'message',
928
 
    'F':                      'file', 
929
1664
    'r':                      'revision',
930
1665
    'v':                      'verbose',
 
1666
    'l':                      'long',
931
1667
}
932
1668
 
933
1669
 
947
1683
    (['status'], {'all': True})
948
1684
    >>> parse_args('commit --message=biter'.split())
949
1685
    (['commit'], {'message': u'biter'})
 
1686
    >>> parse_args('log -r 500'.split())
 
1687
    (['log'], {'revision': [500]})
 
1688
    >>> parse_args('log -r500..600'.split())
 
1689
    (['log'], {'revision': [500, 600]})
 
1690
    >>> parse_args('log -vr500..600'.split())
 
1691
    (['log'], {'verbose': True, 'revision': [500, 600]})
 
1692
    >>> parse_args('log -rv500..600'.split()) #the r takes an argument
 
1693
    (['log'], {'revision': ['v500', 600]})
950
1694
    """
951
1695
    args = []
952
1696
    opts = {}
966
1710
                else:
967
1711
                    optname = a[2:]
968
1712
                if optname not in OPTIONS:
969
 
                    bailout('unknown long option %r' % a)
 
1713
                    raise BzrError('unknown long option %r' % a)
970
1714
            else:
971
1715
                shortopt = a[1:]
972
 
                if shortopt not in SHORT_OPTIONS:
973
 
                    bailout('unknown short option %r' % a)
974
 
                optname = SHORT_OPTIONS[shortopt]
 
1716
                if shortopt in SHORT_OPTIONS:
 
1717
                    # Multi-character options must have a space to delimit
 
1718
                    # their value
 
1719
                    optname = SHORT_OPTIONS[shortopt]
 
1720
                else:
 
1721
                    # Single character short options, can be chained,
 
1722
                    # and have their value appended to their name
 
1723
                    shortopt = a[1:2]
 
1724
                    if shortopt not in SHORT_OPTIONS:
 
1725
                        # We didn't find the multi-character name, and we
 
1726
                        # didn't find the single char name
 
1727
                        raise BzrError('unknown short option %r' % a)
 
1728
                    optname = SHORT_OPTIONS[shortopt]
 
1729
 
 
1730
                    if a[2:]:
 
1731
                        # There are extra things on this option
 
1732
                        # see if it is the value, or if it is another
 
1733
                        # short option
 
1734
                        optargfn = OPTIONS[optname]
 
1735
                        if optargfn is None:
 
1736
                            # This option does not take an argument, so the
 
1737
                            # next entry is another short option, pack it back
 
1738
                            # into the list
 
1739
                            argv.insert(0, '-' + a[2:])
 
1740
                        else:
 
1741
                            # This option takes an argument, so pack it
 
1742
                            # into the array
 
1743
                            optarg = a[2:]
975
1744
            
976
1745
            if optname in opts:
977
1746
                # XXX: Do we ever want to support this, e.g. for -r?
978
 
                bailout('repeated option %r' % a)
 
1747
                raise BzrError('repeated option %r' % a)
979
1748
                
980
1749
            optargfn = OPTIONS[optname]
981
1750
            if optargfn:
982
1751
                if optarg == None:
983
1752
                    if not argv:
984
 
                        bailout('option %r needs an argument' % a)
 
1753
                        raise BzrError('option %r needs an argument' % a)
985
1754
                    else:
986
1755
                        optarg = argv.pop(0)
987
1756
                opts[optname] = optargfn(optarg)
988
1757
            else:
989
1758
                if optarg != None:
990
 
                    bailout('option %r takes no argument' % optname)
 
1759
                    raise BzrError('option %r takes no argument' % optname)
991
1760
                opts[optname] = True
992
1761
        else:
993
1762
            args.append(a)
1047
1816
 
1048
1817
    This is similar to main(), but without all the trappings for
1049
1818
    logging and error handling.  
 
1819
    
 
1820
    argv
 
1821
       The command-line arguments, without the program name from argv[0]
 
1822
    
 
1823
    Returns a command status or raises an exception.
 
1824
 
 
1825
    Special master options: these must come before the command because
 
1826
    they control how the command is interpreted.
 
1827
 
 
1828
    --no-plugins
 
1829
        Do not load plugin modules at all
 
1830
 
 
1831
    --builtin
 
1832
        Only use builtin commands.  (Plugins are still allowed to change
 
1833
        other behaviour.)
 
1834
 
 
1835
    --profile
 
1836
        Run under the Python profiler.
1050
1837
    """
 
1838
    
1051
1839
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
1052
 
    
1053
 
    try:
1054
 
        args, opts = parse_args(argv[1:])
1055
 
        if 'help' in opts:
1056
 
            import help
1057
 
            if args:
1058
 
                help.help(args[0])
1059
 
            else:
1060
 
                help.help()
1061
 
            return 0
1062
 
        elif 'version' in opts:
1063
 
            show_version()
1064
 
            return 0
1065
 
        cmd = str(args.pop(0))
1066
 
    except IndexError:
1067
 
        import help
1068
 
        help.help()
1069
 
        return 1
1070
 
          
1071
 
 
1072
 
    canonical_cmd, cmd_class = get_cmd_class(cmd)
1073
 
 
1074
 
    # global option
1075
 
    if 'profile' in opts:
1076
 
        profile = True
1077
 
        del opts['profile']
1078
 
    else:
1079
 
        profile = False
 
1840
 
 
1841
    opt_profile = opt_no_plugins = opt_builtin = False
 
1842
 
 
1843
    # --no-plugins is handled specially at a very early stage. We need
 
1844
    # to load plugins before doing other command parsing so that they
 
1845
    # can override commands, but this needs to happen first.
 
1846
 
 
1847
    for a in argv[:]:
 
1848
        if a == '--profile':
 
1849
            opt_profile = True
 
1850
        elif a == '--no-plugins':
 
1851
            opt_no_plugins = True
 
1852
        elif a == '--builtin':
 
1853
            opt_builtin = True
 
1854
        else:
 
1855
            break
 
1856
        argv.remove(a)
 
1857
 
 
1858
    if not opt_no_plugins:
 
1859
        from bzrlib.plugin import load_plugins
 
1860
        load_plugins()
 
1861
 
 
1862
    args, opts = parse_args(argv)
 
1863
 
 
1864
    if 'help' in opts:
 
1865
        from bzrlib.help import help
 
1866
        if args:
 
1867
            help(args[0])
 
1868
        else:
 
1869
            help()
 
1870
        return 0            
 
1871
        
 
1872
    if 'version' in opts:
 
1873
        show_version()
 
1874
        return 0
 
1875
    
 
1876
    if not args:
 
1877
        from bzrlib.help import help
 
1878
        help(None)
 
1879
        return 0
 
1880
    
 
1881
    cmd = str(args.pop(0))
 
1882
 
 
1883
    canonical_cmd, cmd_class = \
 
1884
                   get_cmd_class(cmd, plugins_override=not opt_builtin)
1080
1885
 
1081
1886
    # check options are reasonable
1082
1887
    allowed = cmd_class.takes_options
1091
1896
    for k, v in opts.items():
1092
1897
        cmdopts[k.replace('-', '_')] = v
1093
1898
 
1094
 
    if profile:
 
1899
    if opt_profile:
1095
1900
        import hotshot, tempfile
1096
1901
        pffileno, pfname = tempfile.mkstemp()
1097
1902
        try:
1113
1918
            os.close(pffileno)
1114
1919
            os.remove(pfname)
1115
1920
    else:
1116
 
        cmdobj = cmd_class(cmdopts, cmdargs).status 
 
1921
        return cmd_class(cmdopts, cmdargs).status 
1117
1922
 
1118
1923
 
1119
1924
def _report_exception(summary, quiet=False):
1120
1925
    import traceback
 
1926
    
1121
1927
    log_error('bzr: ' + summary)
1122
 
    bzrlib.trace.log_exception()
1123
1928
 
1124
1929
    if not quiet:
 
1930
        sys.stderr.write('\n')
1125
1931
        tb = sys.exc_info()[2]
1126
1932
        exinfo = traceback.extract_tb(tb)
1127
1933
        if exinfo:
1131
1937
 
1132
1938
 
1133
1939
def main(argv):
1134
 
    import errno
1135
 
    
1136
 
    bzrlib.open_tracefile(argv)
 
1940
    bzrlib.trace.open_tracefile(argv)
1137
1941
 
1138
1942
    try:
1139
1943
        try:
1140
 
            try:
1141
 
                return run_bzr(argv)
1142
 
            finally:
1143
 
                # do this here inside the exception wrappers to catch EPIPE
1144
 
                sys.stdout.flush()
1145
 
        except BzrError, e:
1146
 
            quiet = isinstance(e, (BzrCommandError))
1147
 
            _report_exception('error: ' + e.args[0], quiet=quiet)
1148
 
            if len(e.args) > 1:
1149
 
                for h in e.args[1]:
1150
 
                    # some explanation or hints
1151
 
                    log_error('  ' + h)
1152
 
            return 1
1153
 
        except AssertionError, e:
1154
 
            msg = 'assertion failed'
1155
 
            if str(e):
1156
 
                msg += ': ' + str(e)
1157
 
            _report_exception(msg)
1158
 
            return 2
1159
 
        except KeyboardInterrupt, e:
1160
 
            _report_exception('interrupted', quiet=True)
1161
 
            return 2
1162
 
        except Exception, e:
1163
 
            quiet = False
1164
 
            if (isinstance(e, IOError) 
1165
 
                and hasattr(e, 'errno')
1166
 
                and e.errno == errno.EPIPE):
1167
 
                quiet = True
1168
 
                msg = 'broken pipe'
1169
 
            else:
1170
 
                msg = str(e).rstrip('\n')
1171
 
            _report_exception(msg, quiet)
1172
 
            return 2
1173
 
    finally:
1174
 
        bzrlib.trace.close_trace()
 
1944
            return run_bzr(argv[1:])
 
1945
        finally:
 
1946
            # do this here inside the exception wrappers to catch EPIPE
 
1947
            sys.stdout.flush()
 
1948
    except BzrCommandError, e:
 
1949
        # command line syntax error, etc
 
1950
        log_error(str(e))
 
1951
        return 1
 
1952
    except BzrError, e:
 
1953
        bzrlib.trace.log_exception()
 
1954
        return 1
 
1955
    except AssertionError, e:
 
1956
        bzrlib.trace.log_exception('assertion failed: ' + str(e))
 
1957
        return 3
 
1958
    except KeyboardInterrupt, e:
 
1959
        bzrlib.trace.note('interrupted')
 
1960
        return 2
 
1961
    except Exception, e:
 
1962
        import errno
 
1963
        if (isinstance(e, IOError) 
 
1964
            and hasattr(e, 'errno')
 
1965
            and e.errno == errno.EPIPE):
 
1966
            bzrlib.trace.note('broken pipe')
 
1967
            return 2
 
1968
        else:
 
1969
            bzrlib.trace.log_exception('terminated by exception')
 
1970
            return 2
1175
1971
 
1176
1972
 
1177
1973
if __name__ == '__main__':