~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: Martin Pool
  • Date: 2005-06-29 02:55:33 UTC
  • Revision ID: mbp@sourcefrog.net-20050629025533-c8fb62423361c8a2
Patch from John:

- StringIO mixes poorly with difflib

Show diffs side-by-side

added added

removed removed

Lines of Context:
16
16
 
17
17
 
18
18
 
19
 
import sys, os, time, os.path
20
 
from sets import Set
 
19
import sys, os
21
20
 
22
21
import bzrlib
23
22
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, WorkingTree, Tree
27
 
from bzrlib.revision import Revision
28
 
from bzrlib import Branch, Inventory, InventoryEntry, ScratchBranch, BZRDIR, \
29
 
     format_date
 
23
from bzrlib.errors import BzrError, BzrCheckError, BzrCommandError
 
24
from bzrlib.branch import find_branch
 
25
from bzrlib import BZRDIR
 
26
 
 
27
 
 
28
plugin_cmds = {}
 
29
 
 
30
 
 
31
def register_command(cmd):
 
32
    "Utility function to help register a command"
 
33
    global plugin_cmds
 
34
    k = cmd.__name__
 
35
    if k.startswith("cmd_"):
 
36
        k_unsquished = _unsquish_command_name(k)
 
37
    else:
 
38
        k_unsquished = k
 
39
    if not plugin_cmds.has_key(k_unsquished):
 
40
        plugin_cmds[k_unsquished] = cmd
 
41
    else:
 
42
        log_error('Two plugins defined the same command: %r' % k)
 
43
        log_error('Not loading the one in %r' % sys.modules[cmd.__module__])
30
44
 
31
45
 
32
46
def _squish_command_name(cmd):
37
51
    assert cmd.startswith("cmd_")
38
52
    return cmd[4:].replace('_','-')
39
53
 
40
 
def get_all_cmds():
41
 
    """Return canonical name and class for all registered commands."""
 
54
def _parse_revision_str(revstr):
 
55
    """This handles a revision string -> revno. 
 
56
 
 
57
    There are several possibilities:
 
58
 
 
59
        '234'       -> 234
 
60
        '234:345'   -> [234, 345]
 
61
        ':234'      -> [None, 234]
 
62
        '234:'      -> [234, None]
 
63
 
 
64
    In the future we will also support:
 
65
        'uuid:blah-blah-blah'   -> ?
 
66
        'hash:blahblahblah'     -> ?
 
67
        potentially:
 
68
        'tag:mytag'             -> ?
 
69
    """
 
70
    if revstr.find(':') != -1:
 
71
        revs = revstr.split(':')
 
72
        if len(revs) > 2:
 
73
            raise ValueError('More than 2 pieces not supported for --revision: %r' % revstr)
 
74
 
 
75
        if not revs[0]:
 
76
            revs[0] = None
 
77
        else:
 
78
            revs[0] = int(revs[0])
 
79
 
 
80
        if not revs[1]:
 
81
            revs[1] = None
 
82
        else:
 
83
            revs[1] = int(revs[1])
 
84
    else:
 
85
        revs = int(revstr)
 
86
    return revs
 
87
 
 
88
 
 
89
 
 
90
def _get_cmd_dict(plugins_override=True):
 
91
    d = {}
42
92
    for k, v in globals().iteritems():
43
93
        if k.startswith("cmd_"):
44
 
            yield _unsquish_command_name(k), v
45
 
 
46
 
def get_cmd_class(cmd):
 
94
            d[_unsquish_command_name(k)] = v
 
95
    # If we didn't load plugins, the plugin_cmds dict will be empty
 
96
    if plugins_override:
 
97
        d.update(plugin_cmds)
 
98
    else:
 
99
        d2 = plugin_cmds.copy()
 
100
        d2.update(d)
 
101
        d = d2
 
102
    return d
 
103
 
 
104
    
 
105
def get_all_cmds(plugins_override=True):
 
106
    """Return canonical name and class for all registered commands."""
 
107
    for k, v in _get_cmd_dict(plugins_override=plugins_override).iteritems():
 
108
        yield k,v
 
109
 
 
110
 
 
111
def get_cmd_class(cmd, plugins_override=True):
47
112
    """Return the canonical name and command class for a command.
48
113
    """
49
114
    cmd = str(cmd)                      # not unicode
50
115
 
51
116
    # first look up this command under the specified name
 
117
    cmds = _get_cmd_dict(plugins_override=plugins_override)
52
118
    try:
53
 
        return cmd, globals()[_squish_command_name(cmd)]
 
119
        return cmd, cmds[cmd]
54
120
    except KeyError:
55
121
        pass
56
122
 
57
123
    # look for any command which claims this as an alias
58
 
    for cmdname, cmdclass in get_all_cmds():
 
124
    for cmdname, cmdclass in cmds.iteritems():
59
125
        if cmd in cmdclass.aliases:
60
126
            return cmdname, cmdclass
61
 
    else:
62
 
        raise BzrCommandError("unknown command %r" % cmd)
63
 
 
64
 
 
65
 
class Command:
 
127
 
 
128
    cmdclass = ExternalCommand.find_command(cmd)
 
129
    if cmdclass:
 
130
        return cmd, cmdclass
 
131
 
 
132
    raise BzrCommandError("unknown command %r" % cmd)
 
133
 
 
134
 
 
135
class Command(object):
66
136
    """Base class for commands.
67
137
 
68
138
    The docstring for an actual command should give a single-line
111
181
        return 0
112
182
 
113
183
 
 
184
class ExternalCommand(Command):
 
185
    """Class to wrap external commands.
 
186
 
 
187
    We cheat a little here, when get_cmd_class() calls us we actually give it back
 
188
    an object we construct that has the appropriate path, help, options etc for the
 
189
    specified command.
 
190
 
 
191
    When run_bzr() tries to instantiate that 'class' it gets caught by the __call__
 
192
    method, which we override to call the Command.__init__ method. That then calls
 
193
    our run method which is pretty straight forward.
 
194
 
 
195
    The only wrinkle is that we have to map bzr's dictionary of options and arguments
 
196
    back into command line options and arguments for the script.
 
197
    """
 
198
 
 
199
    def find_command(cls, cmd):
 
200
        import os.path
 
201
        bzrpath = os.environ.get('BZRPATH', '')
 
202
 
 
203
        for dir in bzrpath.split(os.pathsep):
 
204
            path = os.path.join(dir, cmd)
 
205
            if os.path.isfile(path):
 
206
                return ExternalCommand(path)
 
207
 
 
208
        return None
 
209
 
 
210
    find_command = classmethod(find_command)
 
211
 
 
212
    def __init__(self, path):
 
213
        self.path = path
 
214
 
 
215
        pipe = os.popen('%s --bzr-usage' % path, 'r')
 
216
        self.takes_options = pipe.readline().split()
 
217
 
 
218
        for opt in self.takes_options:
 
219
            if not opt in OPTIONS:
 
220
                raise BzrError("Unknown option '%s' returned by external command %s"
 
221
                               % (opt, path))
 
222
 
 
223
        # TODO: Is there any way to check takes_args is valid here?
 
224
        self.takes_args = pipe.readline().split()
 
225
 
 
226
        if pipe.close() is not None:
 
227
            raise BzrError("Failed funning '%s --bzr-usage'" % path)
 
228
 
 
229
        pipe = os.popen('%s --bzr-help' % path, 'r')
 
230
        self.__doc__ = pipe.read()
 
231
        if pipe.close() is not None:
 
232
            raise BzrError("Failed funning '%s --bzr-help'" % path)
 
233
 
 
234
    def __call__(self, options, arguments):
 
235
        Command.__init__(self, options, arguments)
 
236
        return self
 
237
 
 
238
    def run(self, **kargs):
 
239
        opts = []
 
240
        args = []
 
241
 
 
242
        keys = kargs.keys()
 
243
        keys.sort()
 
244
        for name in keys:
 
245
            optname = name.replace('_','-')
 
246
            value = kargs[name]
 
247
            if OPTIONS.has_key(optname):
 
248
                # it's an option
 
249
                opts.append('--%s' % optname)
 
250
                if value is not None and value is not True:
 
251
                    opts.append(str(value))
 
252
            else:
 
253
                # it's an arg, or arg list
 
254
                if type(value) is not list:
 
255
                    value = [value]
 
256
                for v in value:
 
257
                    if v is not None:
 
258
                        args.append(str(v))
 
259
 
 
260
        self.status = os.spawnv(os.P_WAIT, self.path, [self.path] + opts + args)
 
261
        return self.status
 
262
 
114
263
 
115
264
class cmd_status(Command):
116
265
    """Display status summary.
117
266
 
118
 
    For each file there is a single line giving its file state and name.
119
 
    The name is that in the current revision unless it is deleted or
120
 
    missing, in which case the old name is shown.
 
267
    This reports on versioned and unknown files, reporting them
 
268
    grouped by state.  Possible states are:
 
269
 
 
270
    added
 
271
        Versioned in the working copy but not in the previous revision.
 
272
 
 
273
    removed
 
274
        Versioned in the previous revision but removed or deleted
 
275
        in the working copy.
 
276
 
 
277
    renamed
 
278
        Path of this file changed from the previous revision;
 
279
        the text may also have changed.  This includes files whose
 
280
        parent directory was renamed.
 
281
 
 
282
    modified
 
283
        Text has changed since the previous revision.
 
284
 
 
285
    unchanged
 
286
        Nothing about this file has changed since the previous revision.
 
287
        Only shown with --all.
 
288
 
 
289
    unknown
 
290
        Not versioned and not matching an ignore pattern.
 
291
 
 
292
    To see ignored files use 'bzr ignored'.  For details in the
 
293
    changes to file texts, use 'bzr diff'.
 
294
 
 
295
    If no arguments are specified, the status of the entire working
 
296
    directory is shown.  Otherwise, only the status of the specified
 
297
    files or directories is reported.  If a directory is given, status
 
298
    is reported for everything inside that directory.
121
299
    """
122
 
    takes_options = ['all']
 
300
    takes_args = ['file*']
 
301
    takes_options = ['all', 'show-ids']
123
302
    aliases = ['st', 'stat']
124
303
    
125
 
    def run(self, all=False):
126
 
        #import bzrlib.status
127
 
        #bzrlib.status.tree_status(Branch('.'))
128
 
        Branch('.').show_status(show_all=all)
 
304
    def run(self, all=False, show_ids=False, file_list=None):
 
305
        if file_list:
 
306
            b = find_branch(file_list[0])
 
307
            file_list = [b.relpath(x) for x in file_list]
 
308
            # special case: only one path was given and it's the root
 
309
            # of the branch
 
310
            if file_list == ['']:
 
311
                file_list = None
 
312
        else:
 
313
            b = find_branch('.')
 
314
        import status
 
315
        status.show_status(b, show_unchanged=all, show_ids=show_ids,
 
316
                           specific_files=file_list)
129
317
 
130
318
 
131
319
class cmd_cat_revision(Command):
135
323
    takes_args = ['revision_id']
136
324
    
137
325
    def run(self, revision_id):
138
 
        Branch('.').get_revision(revision_id).write_xml(sys.stdout)
 
326
        from bzrlib.xml import pack_xml
 
327
        pack_xml(find_branch('.').get_revision(revision_id), sys.stdout)
139
328
 
140
329
 
141
330
class cmd_revno(Command):
143
332
 
144
333
    This is equal to the number of revisions on this branch."""
145
334
    def run(self):
146
 
        print Branch('.').revno()
 
335
        print find_branch('.').revno()
147
336
 
148
337
    
149
338
class cmd_add(Command):
168
357
    recursively add that parent, rather than giving an error?
169
358
    """
170
359
    takes_args = ['file+']
171
 
    takes_options = ['verbose']
 
360
    takes_options = ['verbose', 'no-recurse']
172
361
    
173
 
    def run(self, file_list, verbose=False):
174
 
        bzrlib.add.smart_add(file_list, verbose)
175
 
 
176
 
 
177
 
def Relpath(Command):
 
362
    def run(self, file_list, verbose=False, no_recurse=False):
 
363
        from bzrlib.add import smart_add
 
364
        smart_add(file_list, verbose, not no_recurse)
 
365
 
 
366
 
 
367
 
 
368
class cmd_mkdir(Command):
 
369
    """Create a new versioned directory.
 
370
 
 
371
    This is equivalent to creating the directory and then adding it.
 
372
    """
 
373
    takes_args = ['dir+']
 
374
 
 
375
    def run(self, dir_list):
 
376
        b = None
 
377
        
 
378
        for d in dir_list:
 
379
            os.mkdir(d)
 
380
            if not b:
 
381
                b = find_branch(d)
 
382
            b.add([d], verbose=True)
 
383
 
 
384
 
 
385
class cmd_relpath(Command):
178
386
    """Show path of a file relative to root"""
179
 
    takes_args = ('filename')
 
387
    takes_args = ['filename']
 
388
    hidden = True
180
389
    
181
 
    def run(self):
182
 
        print Branch(self.args['filename']).relpath(filename)
 
390
    def run(self, filename):
 
391
        print find_branch(filename).relpath(filename)
183
392
 
184
393
 
185
394
 
186
395
class cmd_inventory(Command):
187
396
    """Show inventory of the current working copy or a revision."""
188
 
    takes_options = ['revision']
 
397
    takes_options = ['revision', 'show-ids']
189
398
    
190
 
    def run(self, revision=None):
191
 
        b = Branch('.')
 
399
    def run(self, revision=None, show_ids=False):
 
400
        b = find_branch('.')
192
401
        if revision == None:
193
402
            inv = b.read_working_inventory()
194
403
        else:
195
404
            inv = b.get_revision_inventory(b.lookup_revision(revision))
196
405
 
197
 
        for path, entry in inv.iter_entries():
198
 
            print '%-50s %s' % (entry.file_id, path)
 
406
        for path, entry in inv.entries():
 
407
            if show_ids:
 
408
                print '%-50s %s' % (path, entry.file_id)
 
409
            else:
 
410
                print path
199
411
 
200
412
 
201
413
class cmd_move(Command):
208
420
    """
209
421
    takes_args = ['source$', 'dest']
210
422
    def run(self, source_list, dest):
211
 
        b = Branch('.')
 
423
        b = find_branch('.')
212
424
 
213
425
        b.move([b.relpath(s) for s in source_list], b.relpath(dest))
214
426
 
230
442
    takes_args = ['from_name', 'to_name']
231
443
    
232
444
    def run(self, from_name, to_name):
233
 
        b = Branch('.')
 
445
        b = find_branch('.')
234
446
        b.rename_one(b.relpath(from_name), b.relpath(to_name))
235
447
 
236
448
 
237
449
 
 
450
 
 
451
 
 
452
class cmd_pull(Command):
 
453
    """Pull any changes from another branch into the current one.
 
454
 
 
455
    If the location is omitted, the last-used location will be used.
 
456
    Both the revision history and the working directory will be
 
457
    updated.
 
458
 
 
459
    This command only works on branches that have not diverged.  Branches are
 
460
    considered diverged if both branches have had commits without first
 
461
    pulling from the other.
 
462
 
 
463
    If branches have diverged, you can use 'bzr merge' to pull the text changes
 
464
    from one into the other.
 
465
    """
 
466
    takes_args = ['location?']
 
467
 
 
468
    def run(self, location=None):
 
469
        from bzrlib.merge import merge
 
470
        import tempfile
 
471
        from shutil import rmtree
 
472
        import errno
 
473
        
 
474
        br_to = find_branch('.')
 
475
        stored_loc = None
 
476
        try:
 
477
            stored_loc = br_to.controlfile("x-pull", "rb").read().rstrip('\n')
 
478
        except IOError, e:
 
479
            if e.errno != errno.ENOENT:
 
480
                raise
 
481
        if location is None:
 
482
            if stored_loc is None:
 
483
                raise BzrCommandError("No pull location known or specified.")
 
484
            else:
 
485
                print "Using last location: %s" % stored_loc
 
486
                location = stored_loc
 
487
        cache_root = tempfile.mkdtemp()
 
488
        from bzrlib.branch import DivergedBranches
 
489
        br_from = find_branch(location)
 
490
        location = pull_loc(br_from)
 
491
        old_revno = br_to.revno()
 
492
        try:
 
493
            from branch import find_cached_branch, DivergedBranches
 
494
            br_from = find_cached_branch(location, cache_root)
 
495
            location = pull_loc(br_from)
 
496
            old_revno = br_to.revno()
 
497
            try:
 
498
                br_to.update_revisions(br_from)
 
499
            except DivergedBranches:
 
500
                raise BzrCommandError("These branches have diverged."
 
501
                    "  Try merge.")
 
502
                
 
503
            merge(('.', -1), ('.', old_revno), check_clean=False)
 
504
            if location != stored_loc:
 
505
                br_to.controlfile("x-pull", "wb").write(location + "\n")
 
506
        finally:
 
507
            rmtree(cache_root)
 
508
 
 
509
 
 
510
 
 
511
class cmd_branch(Command):
 
512
    """Create a new copy of a branch.
 
513
 
 
514
    If the TO_LOCATION is omitted, the last component of the FROM_LOCATION will
 
515
    be used.  In other words, "branch ../foo/bar" will attempt to create ./bar.
 
516
 
 
517
    To retrieve the branch as of a particular revision, supply the --revision
 
518
    parameter, as in "branch foo/bar -r 5".
 
519
    """
 
520
    takes_args = ['from_location', 'to_location?']
 
521
    takes_options = ['revision']
 
522
 
 
523
    def run(self, from_location, to_location=None, revision=None):
 
524
        import errno
 
525
        from bzrlib.merge import merge
 
526
        from bzrlib.branch import DivergedBranches, NoSuchRevision, \
 
527
             find_cached_branch, Branch
 
528
        from shutil import rmtree
 
529
        from meta_store import CachedStore
 
530
        import tempfile
 
531
        cache_root = tempfile.mkdtemp()
 
532
        try:
 
533
            try:
 
534
                br_from = find_cached_branch(from_location, cache_root)
 
535
            except OSError, e:
 
536
                if e.errno == errno.ENOENT:
 
537
                    raise BzrCommandError('Source location "%s" does not'
 
538
                                          ' exist.' % to_location)
 
539
                else:
 
540
                    raise
 
541
 
 
542
            if to_location is None:
 
543
                to_location = os.path.basename(from_location.rstrip("/\\"))
 
544
 
 
545
            try:
 
546
                os.mkdir(to_location)
 
547
            except OSError, e:
 
548
                if e.errno == errno.EEXIST:
 
549
                    raise BzrCommandError('Target directory "%s" already'
 
550
                                          ' exists.' % to_location)
 
551
                if e.errno == errno.ENOENT:
 
552
                    raise BzrCommandError('Parent of "%s" does not exist.' %
 
553
                                          to_location)
 
554
                else:
 
555
                    raise
 
556
            br_to = Branch(to_location, init=True)
 
557
 
 
558
            try:
 
559
                br_to.update_revisions(br_from, stop_revision=revision)
 
560
            except NoSuchRevision:
 
561
                rmtree(to_location)
 
562
                msg = "The branch %s has no revision %d." % (from_location,
 
563
                                                             revision)
 
564
                raise BzrCommandError(msg)
 
565
            merge((to_location, -1), (to_location, 0), this_dir=to_location,
 
566
                  check_clean=False, ignore_zero=True)
 
567
            from_location = pull_loc(br_from)
 
568
            br_to.controlfile("x-pull", "wb").write(from_location + "\n")
 
569
        finally:
 
570
            rmtree(cache_root)
 
571
 
 
572
 
 
573
def pull_loc(branch):
 
574
    # TODO: Should perhaps just make attribute be 'base' in
 
575
    # RemoteBranch and Branch?
 
576
    if hasattr(branch, "baseurl"):
 
577
        return branch.baseurl
 
578
    else:
 
579
        return branch.base
 
580
 
 
581
 
 
582
 
238
583
class cmd_renames(Command):
239
584
    """Show list of renamed files.
240
585
 
245
590
    takes_args = ['dir?']
246
591
 
247
592
    def run(self, dir='.'):
248
 
        b = Branch(dir)
 
593
        b = find_branch(dir)
249
594
        old_inv = b.basis_tree().inventory
250
595
        new_inv = b.read_working_inventory()
251
596
 
256
601
 
257
602
 
258
603
class cmd_info(Command):
259
 
    """Show statistical information for this branch"""
260
 
    def run(self):
 
604
    """Show statistical information about a branch."""
 
605
    takes_args = ['branch?']
 
606
    
 
607
    def run(self, branch=None):
261
608
        import info
262
 
        info.show_info(Branch('.'))        
 
609
 
 
610
        b = find_branch(branch)
 
611
        info.show_info(b)
263
612
 
264
613
 
265
614
class cmd_remove(Command):
272
621
    takes_options = ['verbose']
273
622
    
274
623
    def run(self, file_list, verbose=False):
275
 
        b = Branch(file_list[0])
 
624
        b = find_branch(file_list[0])
276
625
        b.remove([b.relpath(f) for f in file_list], verbose=verbose)
277
626
 
278
627
 
286
635
    hidden = True
287
636
    takes_args = ['filename']
288
637
    def run(self, filename):
289
 
        b = Branch(filename)
 
638
        b = find_branch(filename)
290
639
        i = b.inventory.path2id(b.relpath(filename))
291
640
        if i == None:
292
 
            bailout("%r is not a versioned file" % filename)
 
641
            raise BzrError("%r is not a versioned file" % filename)
293
642
        else:
294
643
            print i
295
644
 
302
651
    hidden = True
303
652
    takes_args = ['filename']
304
653
    def run(self, filename):
305
 
        b = Branch(filename)
 
654
        b = find_branch(filename)
306
655
        inv = b.inventory
307
656
        fid = inv.path2id(b.relpath(filename))
308
657
        if fid == None:
309
 
            bailout("%r is not a versioned file" % filename)
 
658
            raise BzrError("%r is not a versioned file" % filename)
310
659
        for fip in inv.get_idpath(fid):
311
660
            print fip
312
661
 
313
662
 
314
663
class cmd_revision_history(Command):
315
664
    """Display list of revision ids on this branch."""
 
665
    hidden = True
316
666
    def run(self):
317
 
        for patchid in Branch('.').revision_history():
 
667
        for patchid in find_branch('.').revision_history():
318
668
            print patchid
319
669
 
320
670
 
321
671
class cmd_directories(Command):
322
672
    """Display list of versioned directories in this branch."""
323
673
    def run(self):
324
 
        for name, ie in Branch('.').read_working_inventory().directories():
 
674
        for name, ie in find_branch('.').read_working_inventory().directories():
325
675
            if name == '':
326
676
                print '.'
327
677
            else:
342
692
        bzr commit -m 'imported project'
343
693
    """
344
694
    def run(self):
 
695
        from bzrlib.branch import Branch
345
696
        Branch('.', init=True)
346
697
 
347
698
 
370
721
    """
371
722
    
372
723
    takes_args = ['file*']
373
 
    takes_options = ['revision']
374
 
    aliases = ['di']
 
724
    takes_options = ['revision', 'diff-options']
 
725
    aliases = ['di', 'dif']
375
726
 
376
 
    def run(self, revision=None, file_list=None):
 
727
    def run(self, revision=None, file_list=None, diff_options=None):
377
728
        from bzrlib.diff import show_diff
 
729
 
 
730
        if file_list:
 
731
            b = find_branch(file_list[0])
 
732
            file_list = [b.relpath(f) for f in file_list]
 
733
            if file_list == ['']:
 
734
                # just pointing to top-of-tree
 
735
                file_list = None
 
736
        else:
 
737
            b = find_branch('.')
378
738
    
379
 
        show_diff(Branch('.'), revision, file_list)
 
739
        show_diff(b, revision, specific_files=file_list,
 
740
                  external_diff_options=diff_options)
 
741
 
 
742
 
 
743
        
380
744
 
381
745
 
382
746
class cmd_deleted(Command):
385
749
    TODO: Show files deleted since a previous revision, or between two revisions.
386
750
    """
387
751
    def run(self, show_ids=False):
388
 
        b = Branch('.')
 
752
        b = find_branch('.')
389
753
        old = b.basis_tree()
390
754
        new = b.working_tree()
391
755
 
401
765
                else:
402
766
                    print path
403
767
 
 
768
 
 
769
class cmd_modified(Command):
 
770
    """List files modified in working tree."""
 
771
    hidden = True
 
772
    def run(self):
 
773
        import statcache
 
774
        b = find_branch('.')
 
775
        inv = b.read_working_inventory()
 
776
        sc = statcache.update_cache(b, inv)
 
777
        basis = b.basis_tree()
 
778
        basis_inv = basis.inventory
 
779
        
 
780
        # We used to do this through iter_entries(), but that's slow
 
781
        # when most of the files are unmodified, as is usually the
 
782
        # case.  So instead we iterate by inventory entry, and only
 
783
        # calculate paths as necessary.
 
784
 
 
785
        for file_id in basis_inv:
 
786
            cacheentry = sc.get(file_id)
 
787
            if not cacheentry:                 # deleted
 
788
                continue
 
789
            ie = basis_inv[file_id]
 
790
            if cacheentry[statcache.SC_SHA1] != ie.text_sha1:
 
791
                path = inv.id2path(file_id)
 
792
                print path
 
793
 
 
794
 
 
795
 
 
796
class cmd_added(Command):
 
797
    """List files added in working tree."""
 
798
    hidden = True
 
799
    def run(self):
 
800
        b = find_branch('.')
 
801
        wt = b.working_tree()
 
802
        basis_inv = b.basis_tree().inventory
 
803
        inv = wt.inventory
 
804
        for file_id in inv:
 
805
            if file_id in basis_inv:
 
806
                continue
 
807
            path = inv.id2path(file_id)
 
808
            if not os.access(b.abspath(path), os.F_OK):
 
809
                continue
 
810
            print path
 
811
                
 
812
        
 
813
 
404
814
class cmd_root(Command):
405
815
    """Show the tree root directory.
406
816
 
409
819
    takes_args = ['filename?']
410
820
    def run(self, filename=None):
411
821
        """Print the branch root."""
412
 
        print bzrlib.branch.find_branch_root(filename)
413
 
 
 
822
        b = find_branch(filename)
 
823
        print getattr(b, 'base', None) or getattr(b, 'baseurl')
414
824
 
415
825
 
416
826
class cmd_log(Command):
417
827
    """Show log of this branch.
418
828
 
419
 
    TODO: Options to show ids; to limit range; etc.
 
829
    To request a range of logs, you can use the command -r begin:end
 
830
    -r revision requests a specific revision, -r :end or -r begin: are
 
831
    also valid.
 
832
 
 
833
    TODO: Make --revision support uuid: and hash: [future tag:] notation.
 
834
  
420
835
    """
421
 
    takes_options = ['timezone', 'verbose']
422
 
    def run(self, timezone='original', verbose=False):
423
 
        Branch('.', lock_mode='r').write_log(show_timezone=timezone, verbose=verbose)
 
836
 
 
837
    takes_args = ['filename?']
 
838
    takes_options = ['forward', 'timezone', 'verbose', 'show-ids', 'revision']
 
839
    
 
840
    def run(self, filename=None, timezone='original',
 
841
            verbose=False,
 
842
            show_ids=False,
 
843
            forward=False,
 
844
            revision=None):
 
845
        from bzrlib.branch import find_branch
 
846
        from bzrlib.log import log_formatter, show_log
 
847
        import codecs
 
848
 
 
849
        direction = (forward and 'forward') or 'reverse'
 
850
        
 
851
        if filename:
 
852
            b = find_branch(filename)
 
853
            fp = b.relpath(filename)
 
854
            if fp:
 
855
                file_id = b.read_working_inventory().path2id(fp)
 
856
            else:
 
857
                file_id = None  # points to branch root
 
858
        else:
 
859
            b = find_branch('.')
 
860
            file_id = None
 
861
 
 
862
        if revision == None:
 
863
            revision = [None, None]
 
864
        elif isinstance(revision, int):
 
865
            revision = [revision, revision]
 
866
        else:
 
867
            # pair of revisions?
 
868
            pass
 
869
            
 
870
        assert len(revision) == 2
 
871
 
 
872
        mutter('encoding log as %r' % bzrlib.user_encoding)
 
873
 
 
874
        # use 'replace' so that we don't abort if trying to write out
 
875
        # in e.g. the default C locale.
 
876
        outf = codecs.getwriter(bzrlib.user_encoding)(sys.stdout, errors='replace')
 
877
 
 
878
        lf = log_formatter('short',
 
879
                           show_ids=show_ids,
 
880
                           to_file=outf,
 
881
                           show_timezone=timezone)
 
882
 
 
883
        show_log(b,
 
884
                 lf,
 
885
                 file_id,
 
886
                 verbose=verbose,
 
887
                 direction=direction,
 
888
                 start_revision=revision[0],
 
889
                 end_revision=revision[1])
 
890
 
 
891
 
 
892
 
 
893
class cmd_touching_revisions(Command):
 
894
    """Return revision-ids which affected a particular file.
 
895
 
 
896
    A more user-friendly interface is "bzr log FILE"."""
 
897
    hidden = True
 
898
    takes_args = ["filename"]
 
899
    def run(self, filename):
 
900
        b = find_branch(filename)
 
901
        inv = b.read_working_inventory()
 
902
        file_id = inv.path2id(b.relpath(filename))
 
903
        for revno, revision_id, what in bzrlib.log.find_touching_revisions(b, file_id):
 
904
            print "%6d %s" % (revno, what)
424
905
 
425
906
 
426
907
class cmd_ls(Command):
430
911
    """
431
912
    hidden = True
432
913
    def run(self, revision=None, verbose=False):
433
 
        b = Branch('.')
 
914
        b = find_branch('.')
434
915
        if revision == None:
435
916
            tree = b.working_tree()
436
917
        else:
452
933
 
453
934
 
454
935
class cmd_unknowns(Command):
455
 
    """List unknown files"""
 
936
    """List unknown files."""
456
937
    def run(self):
457
 
        for f in Branch('.').unknowns():
 
938
        from bzrlib.osutils import quotefn
 
939
        for f in find_branch('.').unknowns():
458
940
            print quotefn(f)
459
941
 
460
942
 
461
943
 
462
944
class cmd_ignore(Command):
463
 
    """Ignore a command or pattern"""
 
945
    """Ignore a command or pattern.
 
946
 
 
947
    To remove patterns from the ignore list, edit the .bzrignore file.
 
948
 
 
949
    If the pattern contains a slash, it is compared to the whole path
 
950
    from the branch root.  Otherwise, it is comapred to only the last
 
951
    component of the path.
 
952
 
 
953
    Ignore patterns are case-insensitive on case-insensitive systems.
 
954
 
 
955
    Note: wildcards must be quoted from the shell on Unix.
 
956
 
 
957
    examples:
 
958
        bzr ignore ./Makefile
 
959
        bzr ignore '*.class'
 
960
    """
464
961
    takes_args = ['name_pattern']
465
962
    
466
963
    def run(self, name_pattern):
467
 
        b = Branch('.')
468
 
 
469
 
        # XXX: This will fail if it's a hardlink; should use an AtomicFile class.
470
 
        f = open(b.abspath('.bzrignore'), 'at')
471
 
        f.write(name_pattern + '\n')
472
 
        f.close()
 
964
        from bzrlib.atomicfile import AtomicFile
 
965
        import os.path
 
966
 
 
967
        b = find_branch('.')
 
968
        ifn = b.abspath('.bzrignore')
 
969
 
 
970
        if os.path.exists(ifn):
 
971
            f = open(ifn, 'rt')
 
972
            try:
 
973
                igns = f.read().decode('utf-8')
 
974
            finally:
 
975
                f.close()
 
976
        else:
 
977
            igns = ''
 
978
 
 
979
        # TODO: If the file already uses crlf-style termination, maybe
 
980
        # we should use that for the newly added lines?
 
981
 
 
982
        if igns and igns[-1] != '\n':
 
983
            igns += '\n'
 
984
        igns += name_pattern + '\n'
 
985
 
 
986
        try:
 
987
            f = AtomicFile(ifn, 'wt')
 
988
            f.write(igns.encode('utf-8'))
 
989
            f.commit()
 
990
        finally:
 
991
            f.close()
473
992
 
474
993
        inv = b.working_tree().inventory
475
994
        if inv.path2id('.bzrignore'):
481
1000
 
482
1001
 
483
1002
class cmd_ignored(Command):
484
 
    """List ignored files and the patterns that matched them."""
 
1003
    """List ignored files and the patterns that matched them.
 
1004
 
 
1005
    See also: bzr ignore"""
485
1006
    def run(self):
486
 
        tree = Branch('.').working_tree()
 
1007
        tree = find_branch('.').working_tree()
487
1008
        for path, file_class, kind, file_id in tree.list_files():
488
1009
            if file_class != 'I':
489
1010
                continue
497
1018
 
498
1019
    example:
499
1020
        bzr lookup-revision 33
500
 
        """
 
1021
    """
501
1022
    hidden = True
502
1023
    takes_args = ['revno']
503
1024
    
507
1028
        except ValueError:
508
1029
            raise BzrCommandError("not a valid revision-number: %r" % revno)
509
1030
 
510
 
        print Branch('.').lookup_revision(revno)
 
1031
        print find_branch('.').lookup_revision(revno)
511
1032
 
512
1033
 
513
1034
class cmd_export(Command):
514
1035
    """Export past revision to destination directory.
515
1036
 
516
 
    If no revision is specified this exports the last committed revision."""
 
1037
    If no revision is specified this exports the last committed revision.
 
1038
 
 
1039
    Format may be an "exporter" name, such as tar, tgz, tbz2.  If none is
 
1040
    given, exports to a directory (equivalent to --format=dir)."""
 
1041
    # TODO: list known exporters
517
1042
    takes_args = ['dest']
518
 
    takes_options = ['revision']
519
 
    def run(self, dest, revno=None):
520
 
        b = Branch('.')
521
 
        if revno == None:
522
 
            rh = b.revision_history[-1]
 
1043
    takes_options = ['revision', 'format']
 
1044
    def run(self, dest, revision=None, format='dir'):
 
1045
        b = find_branch('.')
 
1046
        if revision == None:
 
1047
            rh = b.revision_history()[-1]
523
1048
        else:
524
 
            rh = b.lookup_revision(int(revno))
 
1049
            rh = b.lookup_revision(int(revision))
525
1050
        t = b.revision_tree(rh)
526
 
        t.export(dest)
 
1051
        t.export(dest, format)
527
1052
 
528
1053
 
529
1054
class cmd_cat(Command):
535
1060
    def run(self, filename, revision=None):
536
1061
        if revision == None:
537
1062
            raise BzrCommandError("bzr cat requires a revision number")
538
 
        b = Branch('.')
 
1063
        b = find_branch('.')
539
1064
        b.print_file(b.relpath(filename), int(revision))
540
1065
 
541
1066
 
550
1075
class cmd_commit(Command):
551
1076
    """Commit changes into a new revision.
552
1077
 
553
 
    TODO: Commit only selected files.
 
1078
    If selected files are specified, only changes to those files are
 
1079
    committed.  If a directory is specified then its contents are also
 
1080
    committed.
 
1081
 
 
1082
    A selected-file commit may fail in some cases where the committed
 
1083
    tree would be invalid, such as trying to commit a file in a
 
1084
    newly-added directory that is not itself committed.
554
1085
 
555
1086
    TODO: Run hooks on tree to-be-committed, and after commit.
556
1087
 
557
1088
    TODO: Strict commit that fails if there are unknown or deleted files.
558
1089
    """
559
 
    takes_options = ['message', 'verbose']
 
1090
    takes_args = ['selected*']
 
1091
    takes_options = ['message', 'file', 'verbose']
560
1092
    aliases = ['ci', 'checkin']
561
1093
 
562
 
    def run(self, message=None, verbose=False):
563
 
        if not message:
564
 
            raise BzrCommandError("please specify a commit message")
565
 
        Branch('.').commit(message, verbose=verbose)
 
1094
    def run(self, message=None, file=None, verbose=True, selected_list=None):
 
1095
        from bzrlib.commit import commit
 
1096
        from bzrlib.osutils import get_text_message
 
1097
 
 
1098
        ## Warning: shadows builtin file()
 
1099
        if not message and not file:
 
1100
            import cStringIO
 
1101
            stdout = sys.stdout
 
1102
            catcher = cStringIO.StringIO()
 
1103
            sys.stdout = catcher
 
1104
            cmd_status({"file_list":selected_list}, {})
 
1105
            info = catcher.getvalue()
 
1106
            sys.stdout = stdout
 
1107
            message = get_text_message(info)
 
1108
            
 
1109
            if message is None:
 
1110
                raise BzrCommandError("please specify a commit message",
 
1111
                                      ["use either --message or --file"])
 
1112
        elif message and file:
 
1113
            raise BzrCommandError("please specify either --message or --file")
 
1114
        
 
1115
        if file:
 
1116
            import codecs
 
1117
            message = codecs.open(file, 'rt', bzrlib.user_encoding).read()
 
1118
 
 
1119
        b = find_branch('.')
 
1120
        commit(b, message, verbose=verbose, specific_files=selected_list)
566
1121
 
567
1122
 
568
1123
class cmd_check(Command):
570
1125
 
571
1126
    This command checks various invariants about the branch storage to
572
1127
    detect data corruption or bzr bugs.
573
 
    """
574
 
    takes_args = ['dir?']
575
 
    def run(self, dir='.'):
576
 
        import bzrlib.check
577
 
        bzrlib.check.check(Branch(dir, find_root=False))
 
1128
 
 
1129
    If given the --update flag, it will update some optional fields
 
1130
    to help ensure data consistency.
 
1131
    """
 
1132
    takes_args = ['dir?']
 
1133
 
 
1134
    def run(self, dir='.'):
 
1135
        from bzrlib.check import check
 
1136
        check(find_branch(dir))
 
1137
 
 
1138
 
 
1139
 
 
1140
class cmd_upgrade(Command):
 
1141
    """Upgrade branch storage to current format.
 
1142
 
 
1143
    This should normally be used only after the check command tells
 
1144
    you to run it.
 
1145
    """
 
1146
    takes_args = ['dir?']
 
1147
 
 
1148
    def run(self, dir='.'):
 
1149
        from bzrlib.upgrade import upgrade
 
1150
        upgrade(find_branch(dir))
578
1151
 
579
1152
 
580
1153
 
593
1166
    """Run internal test suite"""
594
1167
    hidden = True
595
1168
    def run(self):
596
 
        failures, tests = 0, 0
597
 
 
598
 
        import doctest, bzrlib.store, bzrlib.tests
599
 
        bzrlib.trace.verbose = False
600
 
 
601
 
        for m in bzrlib.store, bzrlib.inventory, bzrlib.branch, bzrlib.osutils, \
602
 
            bzrlib.tree, bzrlib.tests, bzrlib.commands, bzrlib.add:
603
 
            mf, mt = doctest.testmod(m)
604
 
            failures += mf
605
 
            tests += mt
606
 
            print '%-40s %3d tests' % (m.__name__, mt),
607
 
            if mf:
608
 
                print '%3d FAILED!' % mf
609
 
            else:
610
 
                print
611
 
 
612
 
        print '%-40s %3d tests' % ('total', tests),
613
 
        if failures:
614
 
            print '%3d FAILED!' % failures
615
 
        else:
616
 
            print
617
 
 
 
1169
        from bzrlib.selftest import selftest
 
1170
        return int(not selftest())
618
1171
 
619
1172
 
620
1173
class cmd_version(Command):
621
 
    """Show version of bzr"""
 
1174
    """Show version of bzr."""
622
1175
    def run(self):
623
1176
        show_version()
624
1177
 
625
1178
def show_version():
626
1179
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
 
1180
    # is bzrlib itself in a branch?
 
1181
    bzrrev = bzrlib.get_bzr_revision()
 
1182
    if bzrrev:
 
1183
        print "  (bzr checkout, revision %d {%s})" % bzrrev
627
1184
    print bzrlib.__copyright__
628
1185
    print "http://bazaar-ng.org/"
629
1186
    print
638
1195
    def run(self):
639
1196
        print "it sure does!"
640
1197
 
 
1198
def parse_spec(spec):
 
1199
    """
 
1200
    >>> parse_spec(None)
 
1201
    [None, None]
 
1202
    >>> parse_spec("./")
 
1203
    ['./', None]
 
1204
    >>> parse_spec("../@")
 
1205
    ['..', -1]
 
1206
    >>> parse_spec("../f/@35")
 
1207
    ['../f', 35]
 
1208
    """
 
1209
    if spec is None:
 
1210
        return [None, None]
 
1211
    if '/@' in spec:
 
1212
        parsed = spec.split('/@')
 
1213
        assert len(parsed) == 2
 
1214
        if parsed[1] == "":
 
1215
            parsed[1] = -1
 
1216
        else:
 
1217
            parsed[1] = int(parsed[1])
 
1218
            assert parsed[1] >=0
 
1219
    else:
 
1220
        parsed = [spec, None]
 
1221
    return parsed
 
1222
 
 
1223
 
 
1224
 
 
1225
class cmd_merge(Command):
 
1226
    """Perform a three-way merge of trees.
 
1227
    
 
1228
    The SPEC parameters are working tree or revision specifiers.  Working trees
 
1229
    are specified using standard paths or urls.  No component of a directory
 
1230
    path may begin with '@'.
 
1231
    
 
1232
    Working tree examples: '.', '..', 'foo@', but NOT 'foo/@bar'
 
1233
 
 
1234
    Revisions are specified using a dirname/@revno pair, where dirname is the
 
1235
    branch directory and revno is the revision within that branch.  If no revno
 
1236
    is specified, the latest revision is used.
 
1237
 
 
1238
    Revision examples: './@127', 'foo/@', '../@1'
 
1239
 
 
1240
    The OTHER_SPEC parameter is required.  If the BASE_SPEC parameter is
 
1241
    not supplied, the common ancestor of OTHER_SPEC the current branch is used
 
1242
    as the BASE.
 
1243
 
 
1244
    merge refuses to run if there are any uncommitted changes, unless
 
1245
    --force is given.
 
1246
    """
 
1247
    takes_args = ['other_spec', 'base_spec?']
 
1248
    takes_options = ['force']
 
1249
 
 
1250
    def run(self, other_spec, base_spec=None, force=False):
 
1251
        from bzrlib.merge import merge
 
1252
        merge(parse_spec(other_spec), parse_spec(base_spec),
 
1253
              check_clean=(not force))
 
1254
 
 
1255
 
 
1256
 
 
1257
class cmd_revert(Command):
 
1258
    """Restore selected files from a previous revision.
 
1259
    """
 
1260
    takes_args = ['file+']
 
1261
    def run(self, file_list):
 
1262
        from bzrlib.branch import find_branch
 
1263
        
 
1264
        if not file_list:
 
1265
            file_list = ['.']
 
1266
            
 
1267
        b = find_branch(file_list[0])
 
1268
 
 
1269
        b.revert([b.relpath(f) for f in file_list])
 
1270
 
 
1271
 
 
1272
class cmd_merge_revert(Command):
 
1273
    """Reverse all changes since the last commit.
 
1274
 
 
1275
    Only versioned files are affected.
 
1276
 
 
1277
    TODO: Store backups of any files that will be reverted, so
 
1278
          that the revert can be undone.          
 
1279
    """
 
1280
    takes_options = ['revision']
 
1281
 
 
1282
    def run(self, revision=-1):
 
1283
        from bzrlib.merge import merge
 
1284
        merge(('.', revision), parse_spec('.'),
 
1285
              check_clean=False,
 
1286
              ignore_zero=True)
 
1287
 
641
1288
 
642
1289
class cmd_assert_fail(Command):
643
1290
    """Test reporting of assertion failures"""
658
1305
        help.help(topic)
659
1306
 
660
1307
 
661
 
######################################################################
662
 
# main routine
 
1308
class cmd_update_stat_cache(Command):
 
1309
    """Update stat-cache mapping inodes to SHA-1 hashes.
 
1310
 
 
1311
    For testing only."""
 
1312
    hidden = True
 
1313
    def run(self):
 
1314
        import statcache
 
1315
        b = find_branch('.')
 
1316
        statcache.update_cache(b.base, b.read_working_inventory())
 
1317
 
 
1318
 
 
1319
 
 
1320
class cmd_plugins(Command):
 
1321
    """List plugins"""
 
1322
    hidden = True
 
1323
    def run(self):
 
1324
        import bzrlib.plugin
 
1325
        from pprint import pprint
 
1326
        pprint(bzrlib.plugin.all_plugins)
 
1327
 
663
1328
 
664
1329
 
665
1330
# list of all available options; the rhs can be either None for an
667
1332
# the type.
668
1333
OPTIONS = {
669
1334
    'all':                    None,
 
1335
    'diff-options':           str,
670
1336
    'help':                   None,
 
1337
    'file':                   unicode,
 
1338
    'force':                  None,
 
1339
    'format':                 unicode,
 
1340
    'forward':                None,
671
1341
    'message':                unicode,
 
1342
    'no-recurse':             None,
672
1343
    'profile':                None,
673
 
    'revision':               int,
 
1344
    'revision':               _parse_revision_str,
674
1345
    'show-ids':               None,
675
1346
    'timezone':               str,
676
1347
    'verbose':                None,
677
1348
    'version':                None,
678
1349
    'email':                  None,
 
1350
    'update':                 None,
679
1351
    }
680
1352
 
681
1353
SHORT_OPTIONS = {
 
1354
    'F':                      'file', 
 
1355
    'h':                      'help',
682
1356
    'm':                      'message',
683
1357
    'r':                      'revision',
684
1358
    'v':                      'verbose',
701
1375
    (['status'], {'all': True})
702
1376
    >>> parse_args('commit --message=biter'.split())
703
1377
    (['commit'], {'message': u'biter'})
 
1378
    >>> parse_args('log -r 500'.split())
 
1379
    (['log'], {'revision': 500})
 
1380
    >>> parse_args('log -r500:600'.split())
 
1381
    (['log'], {'revision': [500, 600]})
 
1382
    >>> parse_args('log -vr500:600'.split())
 
1383
    (['log'], {'verbose': True, 'revision': [500, 600]})
 
1384
    >>> parse_args('log -rv500:600'.split()) #the r takes an argument
 
1385
    Traceback (most recent call last):
 
1386
    ...
 
1387
    ValueError: invalid literal for int(): v500
704
1388
    """
705
1389
    args = []
706
1390
    opts = {}
720
1404
                else:
721
1405
                    optname = a[2:]
722
1406
                if optname not in OPTIONS:
723
 
                    bailout('unknown long option %r' % a)
 
1407
                    raise BzrError('unknown long option %r' % a)
724
1408
            else:
725
1409
                shortopt = a[1:]
726
 
                if shortopt not in SHORT_OPTIONS:
727
 
                    bailout('unknown short option %r' % a)
728
 
                optname = SHORT_OPTIONS[shortopt]
 
1410
                if shortopt in SHORT_OPTIONS:
 
1411
                    # Multi-character options must have a space to delimit
 
1412
                    # their value
 
1413
                    optname = SHORT_OPTIONS[shortopt]
 
1414
                else:
 
1415
                    # Single character short options, can be chained,
 
1416
                    # and have their value appended to their name
 
1417
                    shortopt = a[1:2]
 
1418
                    if shortopt not in SHORT_OPTIONS:
 
1419
                        # We didn't find the multi-character name, and we
 
1420
                        # didn't find the single char name
 
1421
                        raise BzrError('unknown short option %r' % a)
 
1422
                    optname = SHORT_OPTIONS[shortopt]
 
1423
 
 
1424
                    if a[2:]:
 
1425
                        # There are extra things on this option
 
1426
                        # see if it is the value, or if it is another
 
1427
                        # short option
 
1428
                        optargfn = OPTIONS[optname]
 
1429
                        if optargfn is None:
 
1430
                            # This option does not take an argument, so the
 
1431
                            # next entry is another short option, pack it back
 
1432
                            # into the list
 
1433
                            argv.insert(0, '-' + a[2:])
 
1434
                        else:
 
1435
                            # This option takes an argument, so pack it
 
1436
                            # into the array
 
1437
                            optarg = a[2:]
729
1438
            
730
1439
            if optname in opts:
731
1440
                # XXX: Do we ever want to support this, e.g. for -r?
732
 
                bailout('repeated option %r' % a)
 
1441
                raise BzrError('repeated option %r' % a)
733
1442
                
734
1443
            optargfn = OPTIONS[optname]
735
1444
            if optargfn:
736
1445
                if optarg == None:
737
1446
                    if not argv:
738
 
                        bailout('option %r needs an argument' % a)
 
1447
                        raise BzrError('option %r needs an argument' % a)
739
1448
                    else:
740
1449
                        optarg = argv.pop(0)
741
1450
                opts[optname] = optargfn(optarg)
742
1451
            else:
743
1452
                if optarg != None:
744
 
                    bailout('option %r takes no argument' % optname)
 
1453
                    raise BzrError('option %r takes no argument' % optname)
745
1454
                opts[optname] = True
746
1455
        else:
747
1456
            args.append(a)
795
1504
    return argdict
796
1505
 
797
1506
 
 
1507
def _parse_master_args(argv):
 
1508
    """Parse the arguments that always go with the original command.
 
1509
    These are things like bzr --no-plugins, etc.
 
1510
 
 
1511
    There are now 2 types of option flags. Ones that come *before* the command,
 
1512
    and ones that come *after* the command.
 
1513
    Ones coming *before* the command are applied against all possible commands.
 
1514
    And are generally applied before plugins are loaded.
 
1515
 
 
1516
    The current list are:
 
1517
        --builtin   Allow plugins to load, but don't let them override builtin commands,
 
1518
                    they will still be allowed if they do not override a builtin.
 
1519
        --no-plugins    Don't load any plugins. This lets you get back to official source
 
1520
                        behavior.
 
1521
        --profile   Enable the hotspot profile before running the command.
 
1522
                    For backwards compatibility, this is also a non-master option.
 
1523
        --version   Spit out the version of bzr that is running and exit.
 
1524
                    This is also a non-master option.
 
1525
        --help      Run help and exit, also a non-master option (I think that should stay, though)
 
1526
 
 
1527
    >>> argv, opts = _parse_master_args(['bzr', '--test'])
 
1528
    Traceback (most recent call last):
 
1529
    ...
 
1530
    BzrCommandError: Invalid master option: 'test'
 
1531
    >>> argv, opts = _parse_master_args(['bzr', '--version', 'command'])
 
1532
    >>> print argv
 
1533
    ['command']
 
1534
    >>> print opts['version']
 
1535
    True
 
1536
    >>> argv, opts = _parse_master_args(['bzr', '--profile', 'command', '--more-options'])
 
1537
    >>> print argv
 
1538
    ['command', '--more-options']
 
1539
    >>> print opts['profile']
 
1540
    True
 
1541
    >>> argv, opts = _parse_master_args(['bzr', '--no-plugins', 'command'])
 
1542
    >>> print argv
 
1543
    ['command']
 
1544
    >>> print opts['no-plugins']
 
1545
    True
 
1546
    >>> print opts['profile']
 
1547
    False
 
1548
    >>> argv, opts = _parse_master_args(['bzr', 'command', '--profile'])
 
1549
    >>> print argv
 
1550
    ['command', '--profile']
 
1551
    >>> print opts['profile']
 
1552
    False
 
1553
    """
 
1554
    master_opts = {'builtin':False,
 
1555
        'no-plugins':False,
 
1556
        'version':False,
 
1557
        'profile':False,
 
1558
        'help':False
 
1559
    }
 
1560
 
 
1561
    # This is the point where we could hook into argv[0] to determine
 
1562
    # what front-end is supposed to be run
 
1563
    # For now, we are just ignoring it.
 
1564
    cmd_name = argv.pop(0)
 
1565
    for arg in argv[:]:
 
1566
        if arg[:2] != '--': # at the first non-option, we return the rest
 
1567
            break
 
1568
        arg = arg[2:] # Remove '--'
 
1569
        if arg not in master_opts:
 
1570
            # We could say that this is not an error, that we should
 
1571
            # just let it be handled by the main section instead
 
1572
            raise BzrCommandError('Invalid master option: %r' % arg)
 
1573
        argv.pop(0) # We are consuming this entry
 
1574
        master_opts[arg] = True
 
1575
    return argv, master_opts
 
1576
 
 
1577
 
798
1578
 
799
1579
def run_bzr(argv):
800
1580
    """Execute a command.
805
1585
    argv = [a.decode(bzrlib.user_encoding) for a in argv]
806
1586
    
807
1587
    try:
808
 
        args, opts = parse_args(argv[1:])
 
1588
        # some options like --builtin and --no-plugins have special effects
 
1589
        argv, master_opts = _parse_master_args(argv)
 
1590
        if not master_opts['no-plugins']:
 
1591
            from bzrlib.plugin import load_plugins
 
1592
            load_plugins()
 
1593
 
 
1594
        args, opts = parse_args(argv)
 
1595
 
 
1596
        if master_opts['help']:
 
1597
            from bzrlib.help import help
 
1598
            if argv:
 
1599
                help(argv[0])
 
1600
            else:
 
1601
                help()
 
1602
            return 0            
 
1603
            
809
1604
        if 'help' in opts:
810
 
            import help
 
1605
            from bzrlib.help import help
811
1606
            if args:
812
 
                help.help(args[0])
 
1607
                help(args[0])
813
1608
            else:
814
 
                help.help()
 
1609
                help()
815
1610
            return 0
816
1611
        elif 'version' in opts:
817
1612
            show_version()
818
1613
            return 0
 
1614
        elif args and args[0] == 'builtin':
 
1615
            include_plugins=False
 
1616
            args = args[1:]
819
1617
        cmd = str(args.pop(0))
820
1618
    except IndexError:
821
 
        log_error('usage: bzr COMMAND')
822
 
        log_error('  try "bzr help"')
 
1619
        import help
 
1620
        help.help()
823
1621
        return 1
824
 
 
825
 
    canonical_cmd, cmd_class = get_cmd_class(cmd)
826
 
 
827
 
    # global option
 
1622
          
 
1623
 
 
1624
    plugins_override = not (master_opts['builtin'])
 
1625
    canonical_cmd, cmd_class = get_cmd_class(cmd, plugins_override=plugins_override)
 
1626
 
 
1627
    profile = master_opts['profile']
 
1628
    # For backwards compatibility, I would rather stick with --profile being a
 
1629
    # master/global option
828
1630
    if 'profile' in opts:
829
1631
        profile = True
830
1632
        del opts['profile']
831
 
    else:
832
 
        profile = False
833
1633
 
834
1634
    # check options are reasonable
835
1635
    allowed = cmd_class.takes_options
836
1636
    for oname in opts:
837
1637
        if oname not in allowed:
838
 
            raise BzrCommandError("option %r is not allowed for command %r"
 
1638
            raise BzrCommandError("option '--%s' is not allowed for command %r"
839
1639
                                  % (oname, cmd))
840
1640
 
841
1641
    # mix arguments and options into one dictionary
866
1666
            os.close(pffileno)
867
1667
            os.remove(pfname)
868
1668
    else:
869
 
        cmdobj = cmd_class(cmdopts, cmdargs).status 
 
1669
        return cmd_class(cmdopts, cmdargs).status 
870
1670
 
871
1671
 
872
1672
def _report_exception(summary, quiet=False):
884
1684
 
885
1685
 
886
1686
def main(argv):
887
 
    import errno
888
1687
    
889
 
    bzrlib.open_tracefile(argv)
 
1688
    bzrlib.trace.open_tracefile(argv)
890
1689
 
891
1690
    try:
892
1691
        try:
913
1712
            _report_exception('interrupted', quiet=True)
914
1713
            return 2
915
1714
        except Exception, e:
 
1715
            import errno
916
1716
            quiet = False
917
 
            if isinstance(e, IOError) and e.errno == errno.EPIPE:
 
1717
            if (isinstance(e, IOError) 
 
1718
                and hasattr(e, 'errno')
 
1719
                and e.errno == errno.EPIPE):
918
1720
                quiet = True
919
1721
                msg = 'broken pipe'
920
1722
            else: