/brz/remove-bazaar

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

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

More work on roundtrip push support.

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#! /usr/bin/python
2
 
 
3
 
 
4
 
# Copyright (C) 2004, 2005 by Martin Pool
5
 
# Copyright (C) 2005 by Canonical Ltd
6
 
 
7
 
 
8
 
# This program is free software; you can redistribute it and/or modify
9
 
# it under the terms of the GNU General Public License as published by
10
 
# the Free Software Foundation; either version 2 of the License, or
11
 
# (at your option) any later version.
12
 
 
13
 
# This program is distributed in the hope that it will be useful,
14
 
# but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 
# GNU General Public License for more details.
17
 
 
18
 
# You should have received a copy of the GNU General Public License
19
 
# along with this program; if not, write to the Free Software
20
 
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21
 
 
22
 
"""Bazaar-NG -- a free distributed version-control tool
23
 
 
24
 
**WARNING: THIS IS AN UNSTABLE DEVELOPMENT VERSION**
25
 
 
26
 
Current limitation include:
27
 
 
28
 
* Metadata format is not stable yet -- you may need to
29
 
  discard history in the future.
30
 
 
31
 
* No handling of subdirectories, symlinks or any non-text files.
32
 
 
33
 
* Insufficient error handling.
34
 
 
35
 
* Many commands unimplemented or partially implemented.
36
 
 
37
 
* Space-inefficient storage.
38
 
 
39
 
* No merge operators yet.
40
 
 
41
 
Interesting commands::
42
 
 
43
 
  bzr help
44
 
       Show summary help screen
45
 
  bzr version
46
 
       Show software version/licence/non-warranty.
47
 
  bzr init
48
 
       Start versioning the current directory
49
 
  bzr add FILE...
50
 
       Make files versioned.
51
 
  bzr log
52
 
       Show revision history.
53
 
  bzr diff
54
 
       Show changes from last revision to working copy.
55
 
  bzr commit -m 'MESSAGE'
56
 
       Store current state as new revision.
57
 
  bzr export REVNO DESTINATION
58
 
       Export the branch state at a previous version.
59
 
  bzr status
60
 
       Show summary of pending changes.
61
 
  bzr remove FILE...
62
 
       Make a file not versioned.
63
 
"""
64
 
 
65
 
# not currently working:
66
 
#  bzr info
67
 
#       Show some information about this branch.
68
 
 
69
 
 
70
 
 
71
 
__copyright__ = "Copyright 2005 Canonical Development Ltd."
72
 
__author__ = "Martin Pool <mbp@canonical.com>"
73
 
__docformat__ = "restructuredtext en"
74
 
__version__ = '0.0.0'
75
 
 
76
 
 
77
 
import sys, os, random, time, sha, sets, types, re, shutil, tempfile
78
 
import traceback, socket, fnmatch, difflib
79
 
from os import path
80
 
from sets import Set
81
 
from pprint import pprint
82
 
from stat import *
83
 
from glob import glob
84
 
 
85
 
import bzrlib
86
 
from bzrlib.store import ImmutableStore
87
 
from bzrlib.trace import mutter, note, log_error
88
 
from bzrlib.errors import bailout, BzrError
89
 
from bzrlib.osutils import quotefn, pumpfile, isdir, isfile
90
 
from bzrlib.tree import RevisionTree, EmptyTree, WorkingTree, Tree
91
 
from bzrlib.revision import Revision
92
 
from bzrlib import Branch, Inventory, InventoryEntry, ScratchBranch, BZRDIR, \
93
 
     format_date
94
 
 
95
 
BZR_DIFF_FORMAT = "## Bazaar-NG diff, format 0 ##\n"
96
 
BZR_PATCHNAME_FORMAT = 'cset:sha1:%s'
97
 
 
98
 
## standard representation
99
 
NONE_STRING = '(none)'
100
 
EMPTY = 'empty'
101
 
 
102
 
 
103
 
## TODO: Perhaps a different version of inventory commands that
104
 
## returns iterators...
105
 
 
106
 
## TODO: Perhaps an AtomicFile class that writes to a temporary file and then renames.
107
 
 
108
 
## TODO: Some kind of locking on branches.  Perhaps there should be a
109
 
## parameter to the branch object saying whether we want a read or
110
 
## write lock; release it from destructor.  Perhaps don't even need a
111
 
## read lock to look at immutable objects?
112
 
 
113
 
## TODO: Perhaps make UUIDs predictable in test mode to make it easier
114
 
## to compare output?
115
 
 
116
 
## TODO: Some kind of global code to generate the right Branch object
117
 
## to work on.  Almost, but not quite all, commands need one, and it
118
 
## can be taken either from their parameters or their working
119
 
## directory.
120
 
 
121
 
 
122
 
 
123
 
def cmd_status(all=False):
124
 
    """Display status summary.
125
 
 
126
 
    For each file there is a single line giving its file state and name.
127
 
    The name is that in the current revision unless it is deleted or
128
 
    missing, in which case the old name is shown.
129
 
 
130
 
    :todo: Don't show unchanged files unless ``--all`` is given?
131
 
    """
132
 
    Branch('.').show_status(show_all=all)
133
 
 
134
 
 
135
 
 
136
 
######################################################################
137
 
# examining history
138
 
def cmd_get_revision(revision_id):
139
 
    Branch('.').get_revision(revision_id).write_xml(sys.stdout)
140
 
 
141
 
 
142
 
def cmd_get_file_text(text_id):
143
 
    """Get contents of a file by hash."""
144
 
    sf = Branch('.').text_store[text_id]
145
 
    pumpfile(sf, sys.stdout)
146
 
 
147
 
 
148
 
 
149
 
######################################################################
150
 
# commands
151
 
    
152
 
 
153
 
def cmd_revno():
154
 
    """Show number of revisions on this branch"""
155
 
    print Branch('.').revno()
156
 
    
157
 
 
158
 
def cmd_add(file_list, verbose=False):
159
 
    """Add specified files.
160
 
    
161
 
    Fails if the files are already added.
162
 
    """
163
 
    Branch('.').add(file_list, verbose=verbose)
164
 
 
165
 
 
166
 
def cmd_inventory(revision=None):
167
 
    """Show inventory of the current working copy."""
168
 
    ## TODO: Also optionally show a previous inventory
169
 
    ## TODO: Format options
170
 
    b = Branch('.')
171
 
    if revision == None:
172
 
        inv = b.read_working_inventory()
173
 
    else:
174
 
        inv = b.get_revision_inventory(b.lookup_revision(revision))
175
 
        
176
 
    for path, entry in inv.iter_entries():
177
 
        print '%-50s %s' % (entry.file_id, path)
178
 
 
179
 
 
180
 
 
181
 
def cmd_info():
182
 
    b = Branch('.')
183
 
    print 'branch format:', b.controlfile('branch-format', 'r').readline().rstrip('\n')
184
 
 
185
 
    def plural(n, base='', pl=None):
186
 
        if n == 1:
187
 
            return base
188
 
        elif pl is not None:
189
 
            return pl
190
 
        else:
191
 
            return 's'
192
 
 
193
 
    count_version_dirs = 0
194
 
 
195
 
    count_status = {'A': 0, 'D': 0, 'M': 0, 'R': 0, '?': 0, 'I': 0, '.': 0}
196
 
    for st_tup in bzrlib.diff_trees(b.basis_tree(), b.working_tree()):
197
 
        fs = st_tup[0]
198
 
        count_status[fs] += 1
199
 
        if fs not in ['I', '?'] and st_tup[4] == 'directory':
200
 
            count_version_dirs += 1
201
 
 
202
 
    print
203
 
    print 'in the working tree:'
204
 
    for name, fs in (('unchanged', '.'),
205
 
                     ('modified', 'M'), ('added', 'A'), ('removed', 'D'),
206
 
                     ('renamed', 'R'), ('unknown', '?'), ('ignored', 'I'),
207
 
                     ):
208
 
        print '  %5d %s' % (count_status[fs], name)
209
 
    print '  %5d versioned subdirector%s' % (count_version_dirs,
210
 
                                             plural(count_version_dirs, 'y', 'ies'))
211
 
 
212
 
    print
213
 
    print 'branch history:'
214
 
    history = b.revision_history()
215
 
    revno = len(history)
216
 
    print '  %5d revision%s' % (revno, plural(revno))
217
 
    committers = Set()
218
 
    for rev in history:
219
 
        committers.add(b.get_revision(rev).committer)
220
 
    print '  %5d committer%s' % (len(committers), plural(len(committers)))
221
 
    if revno > 0:
222
 
        firstrev = b.get_revision(history[0])
223
 
        age = int((time.time() - firstrev.timestamp) / 3600 / 24)
224
 
        print '  %5d day%s old' % (age, plural(age))
225
 
        print '  first revision: %s' % format_date(firstrev.timestamp,
226
 
                                                 firstrev.timezone)
227
 
 
228
 
        lastrev = b.get_revision(history[-1])
229
 
        print '  latest revision: %s' % format_date(lastrev.timestamp,
230
 
                                                    lastrev.timezone)
231
 
        
232
 
    
233
 
 
234
 
 
235
 
def cmd_remove(file_list, verbose=False):
236
 
    Branch('.').remove(file_list, verbose=verbose)
237
 
 
238
 
 
239
 
 
240
 
def cmd_file_id(filename):
241
 
    i = Branch('.').read_working_inventory().path2id(filename)
242
 
    if i is None:
243
 
        bailout("%s is not a versioned file" % filename)
244
 
    else:
245
 
        print i
246
 
 
247
 
 
248
 
def cmd_find_filename(fileid):
249
 
    n = find_filename(fileid)
250
 
    if n is None:
251
 
        bailout("%s is not a live file id" % fileid)
252
 
    else:
253
 
        print n
254
 
 
255
 
 
256
 
def cmd_revision_history():
257
 
    for patchid in Branch('.').revision_history():
258
 
        print patchid
259
 
 
260
 
 
261
 
 
262
 
def cmd_init():
263
 
    # TODO: Check we're not already in a working directory?  At the
264
 
    # moment you'll get an ugly error.
265
 
    
266
 
    # TODO: What if we're in a subdirectory of a branch?  Would like
267
 
    # to allow that, but then the parent may need to understand that
268
 
    # the children have disappeared, or should they be versioned in
269
 
    # both?
270
 
 
271
 
    # TODO: Take an argument/option for branch name.
272
 
    Branch('.', init=True)
273
 
 
274
 
 
275
 
def cmd_diff(revision=None):
276
 
    """Show diff from basis to working copy.
277
 
 
278
 
    :todo: Take one or two revision arguments, look up those trees,
279
 
           and diff them.
280
 
 
281
 
    :todo: Allow diff across branches.
282
 
 
283
 
    :todo: Mangle filenames in diff to be more relevant.
284
 
 
285
 
    :todo: Shouldn't be in the cmd function.
286
 
    """
287
 
 
288
 
    b = Branch('.')
289
 
 
290
 
    if revision == None:
291
 
        old_tree = b.basis_tree()
292
 
    else:
293
 
        old_tree = b.revision_tree(b.lookup_revision(revision))
294
 
        
295
 
    new_tree = b.working_tree()
296
 
    old_inv = old_tree.inventory
297
 
    new_inv = new_tree.inventory
298
 
 
299
 
    # TODO: Options to control putting on a prefix or suffix, perhaps as a format string
300
 
    old_label = ''
301
 
    new_label = ''
302
 
 
303
 
    DEVNULL = '/dev/null'
304
 
    # Windows users, don't panic about this filename -- it is a
305
 
    # special signal to GNU patch that the file should be created or
306
 
    # deleted respectively.
307
 
 
308
 
    # TODO: Generation of pseudo-diffs for added/deleted files could
309
 
    # be usefully made into a much faster special case.
310
 
 
311
 
    # TODO: Better to return them in sorted order I think.
312
 
    
313
 
    for file_state, fid, old_name, new_name, kind in bzrlib.diff_trees(old_tree, new_tree):
314
 
        d = None
315
 
 
316
 
        # Don't show this by default; maybe do it if an option is passed
317
 
        # idlabel = '      {%s}' % fid
318
 
        idlabel = ''
319
 
 
320
 
        # FIXME: Something about the diff format makes patch unhappy
321
 
        # with newly-added files.
322
 
 
323
 
        def diffit(*a, **kw):
324
 
            sys.stdout.writelines(difflib.unified_diff(*a, **kw))
325
 
            print
326
 
        
327
 
        if file_state in ['.', '?', 'I']:
328
 
            continue
329
 
        elif file_state == 'A':
330
 
            print '*** added %s %r' % (kind, new_name)
331
 
            if kind == 'file':
332
 
                diffit([],
333
 
                       new_tree.get_file(fid).readlines(),
334
 
                       fromfile=DEVNULL,
335
 
                       tofile=new_label + new_name + idlabel)
336
 
        elif file_state == 'D':
337
 
            assert isinstance(old_name, types.StringTypes)
338
 
            print '*** deleted %s %r' % (kind, old_name)
339
 
            if kind == 'file':
340
 
                diffit(old_tree.get_file(fid).readlines(), [],
341
 
                       fromfile=old_label + old_name + idlabel,
342
 
                       tofile=DEVNULL)
343
 
        elif file_state in ['M', 'R']:
344
 
            if file_state == 'M':
345
 
                assert kind == 'file'
346
 
                assert old_name == new_name
347
 
                print '*** modified %s %r' % (kind, new_name)
348
 
            elif file_state == 'R':
349
 
                print '*** renamed %s %r => %r' % (kind, old_name, new_name)
350
 
 
351
 
            if kind == 'file':
352
 
                diffit(old_tree.get_file(fid).readlines(),
353
 
                       new_tree.get_file(fid).readlines(),
354
 
                       fromfile=old_label + old_name + idlabel,
355
 
                       tofile=new_label + new_name)
356
 
        else:
357
 
            bailout("can't represent state %s {%s}" % (file_state, fid))
358
 
 
359
 
 
360
 
 
361
 
def cmd_log(timezone='original'):
362
 
    """Show log of this branch.
363
 
 
364
 
    :todo: Options for utc; to show ids; to limit range; etc.
365
 
    """
366
 
    Branch('.').write_log(show_timezone=timezone)
367
 
 
368
 
 
369
 
def cmd_ls(revision=None, verbose=False):
370
 
    """List files in a tree.
371
 
 
372
 
    :todo: Take a revision or remote path and list that tree instead.
373
 
    """
374
 
    b = Branch('.')
375
 
    if revision == None:
376
 
        tree = b.working_tree()
377
 
    else:
378
 
        tree = b.revision_tree(b.lookup_revision(revision))
379
 
        
380
 
    for fp, fc, kind, fid in tree.list_files():
381
 
        if verbose:
382
 
            if kind == 'directory':
383
 
                kindch = '/'
384
 
            elif kind == 'file':
385
 
                kindch = ''
386
 
            else:
387
 
                kindch = '???'
388
 
                
389
 
            print '%-8s %s%s' % (fc, fp, kindch)
390
 
        else:
391
 
            print fp
392
 
    
393
 
    
394
 
 
395
 
def cmd_unknowns():
396
 
    """List unknown files"""
397
 
    for f in Branch('.').unknowns():
398
 
        print quotefn(f)
399
 
 
400
 
 
401
 
def cmd_lookup_revision(revno):
402
 
    try:
403
 
        revno = int(revno)
404
 
    except ValueError:
405
 
        bailout("usage: lookup-revision REVNO",
406
 
                ["REVNO is a non-negative revision number for this branch"])
407
 
 
408
 
    print Branch('.').lookup_revision(revno) or NONE_STRING
409
 
 
410
 
 
411
 
 
412
 
def cmd_export(revno, dest):
413
 
    """Export past revision to destination directory."""
414
 
    b = Branch('.')
415
 
    rh = b.lookup_revision(int(revno))
416
 
    t = b.revision_tree(rh)
417
 
    t.export(dest)
418
 
 
419
 
 
420
 
 
421
 
######################################################################
422
 
# internal/test commands
423
 
 
424
 
 
425
 
def cmd_uuid():
426
 
    """Print a newly-generated UUID."""
427
 
    print uuid()
428
 
 
429
 
 
430
 
 
431
 
def cmd_local_time_offset():
432
 
    print bzrlib.osutils.local_time_offset()
433
 
 
434
 
 
435
 
 
436
 
def cmd_commit(message, verbose=False):
437
 
    Branch('.').commit(message, verbose=verbose)
438
 
 
439
 
 
440
 
def cmd_check():
441
 
    """Check consistency of the branch."""
442
 
    check()
443
 
 
444
 
 
445
 
def cmd_is(pred, *rest):
446
 
    """Test whether PREDICATE is true."""
447
 
    try:
448
 
        cmd_handler = globals()['assert_' + pred.replace('-', '_')]
449
 
    except KeyError:
450
 
        bailout("unknown predicate: %s" % quotefn(pred))
451
 
        
452
 
    try:
453
 
        cmd_handler(*rest)
454
 
    except BzrCheckError:
455
 
        # by default we don't print the message so that this can
456
 
        # be used from shell scripts without producing noise
457
 
        sys.exit(1)
458
 
 
459
 
 
460
 
def cmd_username():
461
 
    print bzrlib.osutils.username()
462
 
 
463
 
 
464
 
def cmd_user_email():
465
 
    print bzrlib.osutils.user_email()
466
 
 
467
 
 
468
 
def cmd_gen_revision_id():
469
 
    import time
470
 
    print bzrlib.branch._gen_revision_id(time.time())
471
 
 
472
 
 
473
 
def cmd_doctest():
474
 
    """Run internal doctest suite"""
475
 
    ## -v, if present, is seen by doctest; the argument is just here
476
 
    ## so our parser doesn't complain
477
 
 
478
 
    ## TODO: --verbose option
479
 
    
480
 
    import bzr, doctest, bzrlib.store
481
 
    bzrlib.trace.verbose = False
482
 
    doctest.testmod(bzr)
483
 
    doctest.testmod(bzrlib.store)
484
 
    doctest.testmod(bzrlib.inventory)
485
 
    doctest.testmod(bzrlib.branch)
486
 
    doctest.testmod(bzrlib.osutils)
487
 
    doctest.testmod(bzrlib.tree)
488
 
 
489
 
    # more strenuous tests;
490
 
    import bzrlib.tests
491
 
    doctest.testmod(bzrlib.tests)
492
 
 
493
 
 
494
 
######################################################################
495
 
# help
496
 
 
497
 
 
498
 
def cmd_help():
499
 
    # TODO: Specific help for particular commands
500
 
    print __doc__
501
 
 
502
 
 
503
 
def cmd_version():
504
 
    print "bzr (bazaar-ng) %s" % __version__
505
 
    print __copyright__
506
 
    print "http://bazaar-ng.org/"
507
 
    print
508
 
    print \
509
 
"""bzr comes with ABSOLUTELY NO WARRANTY.  bzr is free software, and
510
 
you may use, modify and redistribute it under the terms of the GNU 
511
 
General Public License version 2 or later."""
512
 
 
513
 
 
514
 
def cmd_rocks():
515
 
    """Statement of optimism."""
516
 
    print "it sure does!"
517
 
 
518
 
 
519
 
 
520
 
######################################################################
521
 
# main routine
522
 
 
523
 
 
524
 
# list of all available options; the rhs can be either None for an
525
 
# option that takes no argument, or a constructor function that checks
526
 
# the type.
527
 
OPTIONS = {
528
 
    'all':                    None,
529
 
    'help':                   None,
530
 
    'message':                unicode,
531
 
    'revision':               int,
532
 
    'show-ids':               None,
533
 
    'timezone':               str,
534
 
    'verbose':                None,
535
 
    'version':                None,
536
 
    }
537
 
 
538
 
SHORT_OPTIONS = {
539
 
    'm':                      'message',
540
 
    'r':                      'revision',
541
 
    'v':                      'verbose',
542
 
}
543
 
 
544
 
# List of options that apply to particular commands; commands not
545
 
# listed take none.
546
 
cmd_options = {
547
 
    'add':                    ['verbose'],
548
 
    'commit':                 ['message', 'verbose'],
549
 
    'diff':                   ['revision'],
550
 
    'inventory':              ['revision'],
551
 
    'log':                    ['show-ids', 'timezone'],
552
 
    'ls':                     ['revision', 'verbose'],
553
 
    'remove':                 ['verbose'],
554
 
    'status':                 ['all'],
555
 
    }
556
 
 
557
 
 
558
 
cmd_args = {
559
 
    'init':                   [],
560
 
    'add':                    ['file+'],
561
 
    'commit':                 [],
562
 
    'diff':                   [],
563
 
    'file-id':                ['filename'],
564
 
    'get-file-text':          ['text_id'],
565
 
    'get-inventory':          ['inventory_id'],
566
 
    'get-revision':           ['revision_id'],
567
 
    'get-revision-inventory': ['revision_id'],
568
 
    'log':                    [],
569
 
    'lookup-revision':        ['revno'],
570
 
    'export':                 ['revno', 'dest'],
571
 
    'remove':                 ['file+'],
572
 
    'status':                 [],
573
 
    }
574
 
 
575
 
 
576
 
def parse_args(argv):
577
 
    """Parse command line.
578
 
    
579
 
    Arguments and options are parsed at this level before being passed
580
 
    down to specific command handlers.  This routine knows, from a
581
 
    lookup table, something about the available options, what optargs
582
 
    they take, and which commands will accept them.
583
 
 
584
 
    >>> parse_args('--help'.split())
585
 
    ([], {'help': True})
586
 
    >>> parse_args('--version'.split())
587
 
    ([], {'version': True})
588
 
    >>> parse_args('status --all'.split())
589
 
    (['status'], {'all': True})
590
 
    >>> parse_args('commit --message=biter'.split())
591
 
    (['commit'], {'message': u'biter'})
592
 
    """
593
 
    args = []
594
 
    opts = {}
595
 
 
596
 
    # TODO: Maybe handle '--' to end options?
597
 
 
598
 
    while argv:
599
 
        a = argv.pop(0)
600
 
        if a[0] == '-':
601
 
            optarg = None
602
 
            if a[1] == '-':
603
 
                mutter("  got option %r" % a)
604
 
                if '=' in a:
605
 
                    optname, optarg = a[2:].split('=', 1)
606
 
                else:
607
 
                    optname = a[2:]
608
 
                if optname not in OPTIONS:
609
 
                    bailout('unknown long option %r' % a)
610
 
            else:
611
 
                shortopt = a[1:]
612
 
                if shortopt not in SHORT_OPTIONS:
613
 
                    bailout('unknown short option %r' % a)
614
 
                optname = SHORT_OPTIONS[shortopt]
615
 
            
616
 
            if optname in opts:
617
 
                # XXX: Do we ever want to support this, e.g. for -r?
618
 
                bailout('repeated option %r' % a)
619
 
                
620
 
            optargfn = OPTIONS[optname]
621
 
            if optargfn:
622
 
                if optarg == None:
623
 
                    if not argv:
624
 
                        bailout('option %r needs an argument' % a)
625
 
                    else:
626
 
                        optarg = argv.pop(0)
627
 
                opts[optname] = optargfn(optarg)
628
 
                mutter("    option argument %r" % opts[optname])
629
 
            else:
630
 
                if optarg != None:
631
 
                    bailout('option %r takes no argument' % optname)
632
 
                opts[optname] = True
633
 
        else:
634
 
            args.append(a)
635
 
 
636
 
    return args, opts
637
 
 
638
 
 
639
 
 
640
 
def _match_args(cmd, args):
641
 
    """Check non-option arguments match required pattern.
642
 
 
643
 
    >>> _match_args('status', ['asdasdsadasd'])
644
 
    Traceback (most recent call last):
645
 
    ...
646
 
    BzrError: ("extra arguments to command status: ['asdasdsadasd']", [])
647
 
    >>> _match_args('add', ['asdasdsadasd'])
648
 
    {'file_list': ['asdasdsadasd']}
649
 
    >>> _match_args('add', 'abc def gj'.split())
650
 
    {'file_list': ['abc', 'def', 'gj']}
651
 
    """
652
 
    # match argument pattern
653
 
    argform = cmd_args.get(cmd, [])
654
 
    argdict = {}
655
 
    # TODO: Need a way to express 'cp SRC... DEST', where it matches
656
 
    # all but one.
657
 
 
658
 
    for ap in argform:
659
 
        argname = ap[:-1]
660
 
        if ap[-1] == '?':
661
 
            assert 0
662
 
        elif ap[-1] == '*':
663
 
            assert 0
664
 
        elif ap[-1] == '+':
665
 
            if not args:
666
 
                bailout("command %r needs one or more %s"
667
 
                        % (cmd, argname.upper()))
668
 
            else:
669
 
                argdict[argname + '_list'] = args[:]
670
 
                args = []
671
 
        else:
672
 
            # just a plain arg
673
 
            argname = ap
674
 
            if not args:
675
 
                bailout("command %r requires argument %s"
676
 
                        % (cmd, argname.upper()))
677
 
            else:
678
 
                argdict[argname] = args.pop(0)
679
 
            
680
 
    if args:
681
 
        bailout("extra arguments to command %s: %r"
682
 
                % (cmd, args))
683
 
 
684
 
    return argdict
685
 
 
686
 
 
687
 
 
688
 
def run_bzr(argv):
689
 
    """Execute a command.
690
 
 
691
 
    This is similar to main(), but without all the trappings for
692
 
    logging and error handling.
693
 
    """
694
 
    try:
695
 
        args, opts = parse_args(argv[1:])
696
 
        if 'help' in opts:
697
 
            # TODO: pass down other arguments in case they asked for
698
 
            # help on a command name?
699
 
            cmd_help()
700
 
            return 0
701
 
        elif 'version' in opts:
702
 
            cmd_version()
703
 
            return 0
704
 
        cmd = args.pop(0)
705
 
    except IndexError:
706
 
        log_error('usage: bzr COMMAND\n')
707
 
        log_error('  try "bzr help"\n')
708
 
        return 1
709
 
            
710
 
    try:
711
 
        cmd_handler = globals()['cmd_' + cmd.replace('-', '_')]
712
 
    except KeyError:
713
 
        bailout("unknown command " + `cmd`)
714
 
 
715
 
    # TODO: special --profile option to turn on the Python profiler
716
 
 
717
 
    # check options are reasonable
718
 
    allowed = cmd_options.get(cmd, [])
719
 
    for oname in opts:
720
 
        if oname not in allowed:
721
 
            bailout("option %r is not allowed for command %r"
722
 
                    % (oname, cmd))
723
 
 
724
 
    cmdargs = _match_args(cmd, args)
725
 
    cmdargs.update(opts)
726
 
 
727
 
    ret = cmd_handler(**cmdargs) or 0
728
 
 
729
 
 
730
 
 
731
 
def main(argv):
732
 
    ## TODO: Handle command-line options; probably know what options are valid for
733
 
    ## each command
734
 
 
735
 
    ## TODO: If the arguments are wrong, give a usage message rather
736
 
    ## than just a backtrace.
737
 
 
738
 
    try:
739
 
        t = bzrlib.trace._tracefile
740
 
        t.write('-' * 60 + '\n')
741
 
        t.write('bzr invoked at %s\n' % format_date(time.time()))
742
 
        t.write('  by %s on %s\n' % (bzrlib.osutils.username(), socket.gethostname()))
743
 
        t.write('  arguments: %r\n' % argv)
744
 
 
745
 
        starttime = os.times()[4]
746
 
 
747
 
        import platform
748
 
        t.write('  platform: %s\n' % platform.platform())
749
 
        t.write('  python: %s\n' % platform.python_version())
750
 
 
751
 
        ret = run_bzr(argv)
752
 
        
753
 
        times = os.times()
754
 
        mutter("finished, %.3fu/%.3fs cpu, %.3fu/%.3fs cum"
755
 
               % times[:4])
756
 
        mutter("    %.3f elapsed" % (times[4] - starttime))
757
 
 
758
 
        return ret
759
 
    except BzrError, e:
760
 
        log_error('bzr: error: ' + e.args[0] + '\n')
761
 
        if len(e.args) > 1:
762
 
            for h in e.args[1]:
763
 
                log_error('  ' + h + '\n')
764
 
        return 1
765
 
    except Exception, e:
766
 
        log_error('bzr: exception: %s\n' % e)
767
 
        log_error('    see .bzr.log for details\n')
768
 
        traceback.print_exc(None, bzrlib.trace._tracefile)
769
 
        traceback.print_exc(None, sys.stderr)
770
 
        return 1
771
 
 
772
 
    # TODO: Maybe nicer handling of IOError?
773
 
 
774
 
 
775
 
 
776
 
if __name__ == '__main__':
777
 
    sys.exit(main(sys.argv))
778
 
    ##import profile
779
 
    ##profile.run('main(sys.argv)')
780