~bzr-pqm/bzr/bzr.dev

« back to all changes in this revision

Viewing changes to bzrlib/commands.py

  • Committer: mbp at sourcefrog
  • Date: 2005-04-08 22:14:09 UTC
  • Revision ID: mbp@sourcefrog.net-20050408221409-a99bd4796a56f42edbf3f13a
selected-file diff

Show diffs side-by-side

added added

removed removed

Lines of Context:
1
 
#! /usr/bin/python
2
 
 
3
 
 
4
1
# Copyright (C) 2004, 2005 by Martin Pool
5
2
# Copyright (C) 2005 by Canonical Ltd
6
3
 
28
25
* Metadata format is not stable yet -- you may need to
29
26
  discard history in the future.
30
27
 
31
 
* No handling of subdirectories, symlinks or any non-text files.
32
 
 
33
28
* Insufficient error handling.
34
29
 
35
30
* Many commands unimplemented or partially implemented.
40
35
 
41
36
Interesting commands::
42
37
 
43
 
  bzr help
44
 
       Show summary help screen
 
38
  bzr help [COMMAND]
 
39
       Show help screen
45
40
  bzr version
46
41
       Show software version/licence/non-warranty.
47
42
  bzr init
50
45
       Make files versioned.
51
46
  bzr log
52
47
       Show revision history.
53
 
  bzr diff
 
48
  bzr diff [FILE...]
54
49
       Show changes from last revision to working copy.
55
50
  bzr commit -m 'MESSAGE'
56
51
       Store current state as new revision.
60
55
       Show summary of pending changes.
61
56
  bzr remove FILE...
62
57
       Make a file not versioned.
 
58
  bzr info
 
59
       Show statistics about this branch.
63
60
"""
64
61
 
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
 
62
 
 
63
 
 
64
 
 
65
import sys, os, time, types, shutil, tempfile, traceback, fnmatch, difflib, os.path
80
66
from sets import Set
81
67
from pprint import pprint
82
68
from stat import *
85
71
import bzrlib
86
72
from bzrlib.store import ImmutableStore
87
73
from bzrlib.trace import mutter, note, log_error
88
 
from bzrlib.errors import bailout, BzrError
 
74
from bzrlib.errors import bailout, BzrError, BzrCheckError
89
75
from bzrlib.osutils import quotefn, pumpfile, isdir, isfile
90
76
from bzrlib.tree import RevisionTree, EmptyTree, WorkingTree, Tree
91
77
from bzrlib.revision import Revision
165
151
    print Branch('.').revno()
166
152
    
167
153
 
 
154
    
168
155
def cmd_add(file_list, verbose=False):
169
 
    """Add specified files.
 
156
    """Add specified files or directories.
 
157
 
 
158
    In non-recursive mode, all the named items are added, regardless
 
159
    of whether they were previously ignored.  A warning is given if
 
160
    any of the named files are already versioned.
 
161
 
 
162
    In recursive mode (the default), files are treated the same way
 
163
    but the behaviour for directories is different.  Directories that
 
164
    are already versioned do not give a warning.  All directories,
 
165
    whether already versioned or not, are searched for files or
 
166
    subdirectories that are neither versioned or ignored, and these
 
167
    are added.  This search proceeds recursively into versioned
 
168
    directories.
 
169
 
 
170
    Therefore simply saying 'bzr add .' will version all files that
 
171
    are currently unknown.
 
172
    """
 
173
    bzrlib.add.smart_add(file_list, verbose)
170
174
    
171
 
    Fails if the files are already added.
172
 
    """
173
 
    Branch('.').add(file_list, verbose=verbose)
 
175
 
 
176
def cmd_relpath(filename):
 
177
    """Show path of file relative to root"""
 
178
    print Branch(filename).relpath(filename)
 
179
 
174
180
 
175
181
 
176
182
def cmd_inventory(revision=None):
188
194
 
189
195
 
190
196
 
 
197
# TODO: Maybe a 'mv' command that has the combined move/rename
 
198
# special behaviour of Unix?
 
199
 
 
200
def cmd_move(source_list, dest):
 
201
    b = Branch('.')
 
202
 
 
203
    b.move([b.relpath(s) for s in source_list], b.relpath(dest))
 
204
 
 
205
 
 
206
 
 
207
def cmd_rename(from_name, to_name):
 
208
    """Change the name of an entry.
 
209
 
 
210
usage: bzr rename FROM_NAME TO_NAME
 
211
 
 
212
examples:
 
213
  bzr rename frob.c frobber.c
 
214
  bzr rename src/frob.c lib/frob.c
 
215
 
 
216
It is an error if the destination name exists.
 
217
 
 
218
See also the 'move' command, which moves files into a different
 
219
directory without changing their name.
 
220
 
 
221
TODO: Some way to rename multiple files without invoking bzr for each
 
222
one?"""
 
223
    b = Branch('.')
 
224
    b.rename_one(b.relpath(from_name), b.relpath(to_name))
 
225
    
 
226
 
 
227
 
 
228
 
 
229
def cmd_renames(dir='.'):
 
230
    """Show list of renamed files.
 
231
 
 
232
usage: bzr renames [BRANCH]
 
233
 
 
234
TODO: Option to show renames between two historical versions.
 
235
 
 
236
TODO: Only show renames under dir, rather than in the whole branch.
 
237
"""
 
238
    b = Branch(dir)
 
239
    old_inv = b.basis_tree().inventory
 
240
    new_inv = b.read_working_inventory()
 
241
    
 
242
    renames = list(bzrlib.tree.find_renames(old_inv, new_inv))
 
243
    renames.sort()
 
244
    for old_name, new_name in renames:
 
245
        print "%s => %s" % (old_name, new_name)        
 
246
 
 
247
 
 
248
 
191
249
def cmd_info():
192
 
    b = Branch('.')
193
 
    print 'branch format:', b.controlfile('branch-format', 'r').readline().rstrip('\n')
194
 
 
195
 
    def plural(n, base='', pl=None):
196
 
        if n == 1:
197
 
            return base
198
 
        elif pl is not None:
199
 
            return pl
200
 
        else:
201
 
            return 's'
202
 
 
203
 
    count_version_dirs = 0
204
 
 
205
 
    count_status = {'A': 0, 'D': 0, 'M': 0, 'R': 0, '?': 0, 'I': 0, '.': 0}
206
 
    for st_tup in bzrlib.diff_trees(b.basis_tree(), b.working_tree()):
207
 
        fs = st_tup[0]
208
 
        count_status[fs] += 1
209
 
        if fs not in ['I', '?'] and st_tup[4] == 'directory':
210
 
            count_version_dirs += 1
211
 
 
212
 
    print
213
 
    print 'in the working tree:'
214
 
    for name, fs in (('unchanged', '.'),
215
 
                     ('modified', 'M'), ('added', 'A'), ('removed', 'D'),
216
 
                     ('renamed', 'R'), ('unknown', '?'), ('ignored', 'I'),
217
 
                     ):
218
 
        print '  %5d %s' % (count_status[fs], name)
219
 
    print '  %5d versioned subdirector%s' % (count_version_dirs,
220
 
                                             plural(count_version_dirs, 'y', 'ies'))
221
 
 
222
 
    print
223
 
    print 'branch history:'
224
 
    history = b.revision_history()
225
 
    revno = len(history)
226
 
    print '  %5d revision%s' % (revno, plural(revno))
227
 
    committers = Set()
228
 
    for rev in history:
229
 
        committers.add(b.get_revision(rev).committer)
230
 
    print '  %5d committer%s' % (len(committers), plural(len(committers)))
231
 
    if revno > 0:
232
 
        firstrev = b.get_revision(history[0])
233
 
        age = int((time.time() - firstrev.timestamp) / 3600 / 24)
234
 
        print '  %5d day%s old' % (age, plural(age))
235
 
        print '  first revision: %s' % format_date(firstrev.timestamp,
236
 
                                                 firstrev.timezone)
237
 
 
238
 
        lastrev = b.get_revision(history[-1])
239
 
        print '  latest revision: %s' % format_date(lastrev.timestamp,
240
 
                                                    lastrev.timezone)
241
 
        
 
250
    """info: Show statistical information for this branch
 
251
 
 
252
usage: bzr info"""
 
253
    import info
 
254
    info.show_info(Branch('.'))        
242
255
    
243
256
 
244
257
 
245
258
def cmd_remove(file_list, verbose=False):
246
 
    Branch('.').remove(file_list, verbose=verbose)
 
259
    b = Branch(file_list[0])
 
260
    b.remove([b.relpath(f) for f in file_list], verbose=verbose)
247
261
 
248
262
 
249
263
 
250
264
def cmd_file_id(filename):
251
 
    i = Branch('.').read_working_inventory().path2id(filename)
252
 
    if i is None:
253
 
        bailout("%s is not a versioned file" % filename)
 
265
    """Print file_id of a particular file or directory.
 
266
 
 
267
usage: bzr file-id FILE
 
268
 
 
269
The file_id is assigned when the file is first added and remains the
 
270
same through all revisions where the file exists, even when it is
 
271
moved or renamed.
 
272
"""
 
273
    b = Branch(filename)
 
274
    i = b.inventory.path2id(b.relpath(filename))
 
275
    if i == None:
 
276
        bailout("%r is not a versioned file" % filename)
254
277
    else:
255
278
        print i
256
279
 
257
280
 
258
 
def cmd_find_filename(fileid):
259
 
    n = find_filename(fileid)
260
 
    if n is None:
261
 
        bailout("%s is not a live file id" % fileid)
262
 
    else:
263
 
        print n
 
281
def cmd_file_id_path(filename):
 
282
    """Print path of file_ids to a file or directory.
 
283
 
 
284
usage: bzr file-id-path FILE
 
285
 
 
286
This prints one line for each directory down to the target,
 
287
starting at the branch root."""
 
288
    b = Branch(filename)
 
289
    inv = b.inventory
 
290
    fid = inv.path2id(b.relpath(filename))
 
291
    if fid == None:
 
292
        bailout("%r is not a versioned file" % filename)
 
293
    for fip in inv.get_idpath(fid):
 
294
        print fip
264
295
 
265
296
 
266
297
def cmd_revision_history():
268
299
        print patchid
269
300
 
270
301
 
 
302
def cmd_directories():
 
303
    for name, ie in Branch('.').read_working_inventory().directories():
 
304
        if name == '':
 
305
            print '.'
 
306
        else:
 
307
            print name
 
308
 
 
309
 
 
310
def cmd_missing():
 
311
    for name, ie in Branch('.').working_tree().missing():
 
312
        print name
 
313
 
271
314
 
272
315
def cmd_init():
273
316
    # TODO: Check we're not already in a working directory?  At the
282
325
    Branch('.', init=True)
283
326
 
284
327
 
285
 
def cmd_diff(revision=None):
286
 
    """Show diff from basis to working copy.
287
 
 
288
 
    :todo: Take one or two revision arguments, look up those trees,
289
 
           and diff them.
290
 
 
291
 
    :todo: Allow diff across branches.
292
 
 
293
 
    :todo: Mangle filenames in diff to be more relevant.
294
 
 
295
 
    :todo: Shouldn't be in the cmd function.
296
 
    """
 
328
def cmd_diff(revision=None, file_list=None):
 
329
    """bzr diff: Show differences in working tree.
 
330
    
 
331
usage: bzr diff [-r REV] [FILE...]
 
332
 
 
333
--revision REV
 
334
    Show changes since REV, rather than predecessor.
 
335
 
 
336
If files are listed, only the changes in those files are listed.
 
337
Otherwise, all changes for the tree are listed.
 
338
 
 
339
TODO: Given two revision arguments, show the difference between them.
 
340
 
 
341
TODO: Allow diff across branches.
 
342
 
 
343
TODO: Option to use external diff command; could be GNU diff, wdiff,
 
344
or a graphical diff.
 
345
 
 
346
TODO: If a directory is given, diff everything under that.
 
347
 
 
348
TODO: Selected-file diff is inefficient and doesn't show you deleted files.
 
349
"""
 
350
 
 
351
    ## TODO: Shouldn't be in the cmd function.
297
352
 
298
353
    b = Branch('.')
299
354
 
303
358
        old_tree = b.revision_tree(b.lookup_revision(revision))
304
359
        
305
360
    new_tree = b.working_tree()
306
 
    old_inv = old_tree.inventory
307
 
    new_inv = new_tree.inventory
308
361
 
309
362
    # TODO: Options to control putting on a prefix or suffix, perhaps as a format string
310
363
    old_label = ''
319
372
    # be usefully made into a much faster special case.
320
373
 
321
374
    # TODO: Better to return them in sorted order I think.
 
375
 
 
376
    # FIXME: If given a file list, compare only those files rather
 
377
    # than comparing everything and then throwing stuff away.
322
378
    
323
379
    for file_state, fid, old_name, new_name, kind in bzrlib.diff_trees(old_tree, new_tree):
324
 
        d = None
325
380
 
 
381
        if file_list and new_name not in file_list:
 
382
            continue
 
383
        
326
384
        # Don't show this by default; maybe do it if an option is passed
327
385
        # idlabel = '      {%s}' % fid
328
386
        idlabel = ''
330
388
        # FIXME: Something about the diff format makes patch unhappy
331
389
        # with newly-added files.
332
390
 
333
 
        def diffit(*a, **kw):
334
 
            sys.stdout.writelines(difflib.unified_diff(*a, **kw))
 
391
        def diffit(oldlines, newlines, **kw):
 
392
            # FIXME: difflib is wrong if there is no trailing newline.
 
393
 
 
394
            # Special workaround for Python2.3, where difflib fails if
 
395
            # both sequences are empty.
 
396
            if oldlines or newlines:
 
397
                sys.stdout.writelines(difflib.unified_diff(oldlines, newlines, **kw))
335
398
            print
336
399
        
337
400
        if file_state in ['.', '?', 'I']:
368
431
 
369
432
 
370
433
 
 
434
def cmd_deleted(show_ids=False):
 
435
    """List files deleted in the working tree.
 
436
 
 
437
TODO: Show files deleted since a previous revision, or between two revisions.
 
438
    """
 
439
    b = Branch('.')
 
440
    old = b.basis_tree()
 
441
    new = b.working_tree()
 
442
 
 
443
    ## TODO: Much more efficient way to do this: read in new
 
444
    ## directories with readdir, rather than stating each one.  Same
 
445
    ## level of effort but possibly much less IO.  (Or possibly not,
 
446
    ## if the directories are very large...)
 
447
 
 
448
    for path, ie in old.inventory.iter_entries():
 
449
        if not new.has_id(ie.file_id):
 
450
            if show_ids:
 
451
                print '%-50s %s' % (path, ie.file_id)
 
452
            else:
 
453
                print path
 
454
 
 
455
 
 
456
 
 
457
def cmd_parse_inventory():
 
458
    import cElementTree
 
459
    
 
460
    cElementTree.ElementTree().parse(file('.bzr/inventory'))
 
461
 
 
462
 
 
463
 
 
464
def cmd_load_inventory():
 
465
    """Load inventory for timing purposes"""
 
466
    Branch('.').basis_tree().inventory
 
467
 
 
468
 
 
469
def cmd_dump_inventory():
 
470
    Branch('.').read_working_inventory().write_xml(sys.stdout)
 
471
 
 
472
 
 
473
def cmd_dump_new_inventory():
 
474
    import bzrlib.newinventory
 
475
    inv = Branch('.').basis_tree().inventory
 
476
    bzrlib.newinventory.write_inventory(inv, sys.stdout)
 
477
 
 
478
 
 
479
def cmd_load_new_inventory():
 
480
    import bzrlib.newinventory
 
481
    bzrlib.newinventory.read_new_inventory(sys.stdin)
 
482
                
 
483
    
 
484
def cmd_dump_slacker_inventory():
 
485
    import bzrlib.newinventory
 
486
    inv = Branch('.').basis_tree().inventory
 
487
    bzrlib.newinventory.write_slacker_inventory(inv, sys.stdout)
 
488
                
 
489
    
 
490
 
 
491
def cmd_root(filename=None):
 
492
    """Print the branch root."""
 
493
    print bzrlib.branch.find_branch_root(filename)
 
494
    
 
495
 
371
496
def cmd_log(timezone='original'):
372
497
    """Show log of this branch.
373
498
 
408
533
        print quotefn(f)
409
534
 
410
535
 
 
536
 
 
537
def cmd_ignored():
 
538
    """List ignored files and the patterns that matched them.
 
539
      """
 
540
    tree = Branch('.').working_tree()
 
541
    for path, file_class, kind, file_id in tree.list_files():
 
542
        if file_class != 'I':
 
543
            continue
 
544
        ## XXX: Slightly inefficient since this was already calculated
 
545
        pat = tree.is_ignored(path)
 
546
        print '%-50s %s' % (path, pat)
 
547
 
 
548
 
411
549
def cmd_lookup_revision(revno):
412
550
    try:
413
551
        revno = int(revno)
426
564
    t = b.revision_tree(rh)
427
565
    t.export(dest)
428
566
 
 
567
def cmd_cat(revision, filename):
 
568
    """Print file to stdout."""
 
569
    b = Branch('.')
 
570
    b.print_file(b.relpath(filename), int(revision))
429
571
 
430
572
 
431
573
######################################################################
434
576
 
435
577
def cmd_uuid():
436
578
    """Print a newly-generated UUID."""
437
 
    print uuid()
 
579
    print bzrlib.osutils.uuid()
438
580
 
439
581
 
440
582
 
443
585
 
444
586
 
445
587
 
446
 
def cmd_commit(message, verbose=False):
 
588
def cmd_commit(message=None, verbose=False):
 
589
    """Commit changes to a new revision.
 
590
 
 
591
--message MESSAGE
 
592
    Description of changes in this revision; free form text.
 
593
    It is recommended that the first line be a single-sentence
 
594
    summary.
 
595
--verbose
 
596
    Show status of changed files,
 
597
 
 
598
TODO: Commit only selected files.
 
599
 
 
600
TODO: Run hooks on tree to-be-committed, and after commit.
 
601
 
 
602
TODO: Strict commit that fails if there are unknown or deleted files.
 
603
"""
 
604
 
 
605
    if not message:
 
606
        bailout("please specify a commit message")
447
607
    Branch('.').commit(message, verbose=verbose)
448
608
 
449
609
 
450
 
def cmd_check():
451
 
    """Check consistency of the branch."""
452
 
    check()
 
610
def cmd_check(dir='.'):
 
611
    """check: Consistency check of branch history.
 
612
 
 
613
usage: bzr check [-v] [BRANCH]
 
614
 
 
615
options:
 
616
  --verbose, -v         Show progress of checking.
 
617
 
 
618
This command checks various invariants about the branch storage to
 
619
detect data corruption or bzr bugs.
 
620
"""
 
621
    import bzrlib.check
 
622
    bzrlib.check.check(Branch(dir, find_root=False))
453
623
 
454
624
 
455
625
def cmd_is(pred, *rest):
476
646
 
477
647
 
478
648
def cmd_gen_revision_id():
479
 
    import time
480
649
    print bzrlib.branch._gen_revision_id(time.time())
481
650
 
482
651
 
483
 
def cmd_doctest():
484
 
    """Run internal doctest suite"""
 
652
def cmd_selftest():
 
653
    """Run internal test suite"""
485
654
    ## -v, if present, is seen by doctest; the argument is just here
486
655
    ## so our parser doesn't complain
487
656
 
488
657
    ## TODO: --verbose option
 
658
 
 
659
    failures, tests = 0, 0
489
660
    
490
 
    import doctest, bzrlib.store
 
661
    import doctest, bzrlib.store, bzrlib.tests
491
662
    bzrlib.trace.verbose = False
492
 
    doctest.testmod(bzrlib.store)
493
 
    doctest.testmod(bzrlib.inventory)
494
 
    doctest.testmod(bzrlib.branch)
495
 
    doctest.testmod(bzrlib.osutils)
496
 
    doctest.testmod(bzrlib.tree)
497
 
 
498
 
    # more strenuous tests;
499
 
    import bzrlib.tests
500
 
    doctest.testmod(bzrlib.tests)
 
663
 
 
664
    for m in bzrlib.store, bzrlib.inventory, bzrlib.branch, bzrlib.osutils, \
 
665
        bzrlib.tree, bzrlib.tests, bzrlib.commands, bzrlib.add:
 
666
        mf, mt = doctest.testmod(m)
 
667
        failures += mf
 
668
        tests += mt
 
669
        print '%-40s %3d tests' % (m.__name__, mt),
 
670
        if mf:
 
671
            print '%3d FAILED!' % mf
 
672
        else:
 
673
            print
 
674
 
 
675
    print '%-40s %3d tests' % ('total', tests),
 
676
    if failures:
 
677
        print '%3d FAILED!' % failures
 
678
    else:
 
679
        print
 
680
 
 
681
 
 
682
 
 
683
# deprecated
 
684
cmd_doctest = cmd_selftest
501
685
 
502
686
 
503
687
######################################################################
504
688
# help
505
689
 
506
690
 
507
 
def cmd_help():
508
 
    # TODO: Specific help for particular commands
509
 
    print __doc__
 
691
def cmd_help(topic=None):
 
692
    if topic == None:
 
693
        print __doc__
 
694
        return
 
695
 
 
696
    # otherwise, maybe the name of a command?
 
697
    try:
 
698
        cmdfn = globals()['cmd_' + topic.replace('-', '_')]
 
699
    except KeyError:
 
700
        bailout("no help for %r" % topic)
 
701
 
 
702
    doc = cmdfn.__doc__
 
703
    if doc == None:
 
704
        bailout("sorry, no detailed help yet for %r" % topic)
 
705
 
 
706
    print doc
 
707
        
 
708
 
510
709
 
511
710
 
512
711
def cmd_version():
513
 
    print "bzr (bazaar-ng) %s" % __version__
514
 
    print __copyright__
 
712
    print "bzr (bazaar-ng) %s" % bzrlib.__version__
 
713
    print bzrlib.__copyright__
515
714
    print "http://bazaar-ng.org/"
516
715
    print
517
716
    print \
537
736
    'all':                    None,
538
737
    'help':                   None,
539
738
    'message':                unicode,
 
739
    'profile':                None,
540
740
    'revision':               int,
541
741
    'show-ids':               None,
542
742
    'timezone':               str,
554
754
# listed take none.
555
755
cmd_options = {
556
756
    'add':                    ['verbose'],
 
757
    'cat':                    ['revision'],
557
758
    'commit':                 ['message', 'verbose'],
 
759
    'deleted':                ['show-ids'],
558
760
    'diff':                   ['revision'],
559
761
    'inventory':              ['revision'],
560
 
    'log':                    ['show-ids', 'timezone'],
 
762
    'log':                    ['timezone'],
561
763
    'ls':                     ['revision', 'verbose'],
562
764
    'remove':                 ['verbose'],
563
765
    'status':                 ['all'],
565
767
 
566
768
 
567
769
cmd_args = {
568
 
    'init':                   [],
569
770
    'add':                    ['file+'],
 
771
    'cat':                    ['filename'],
570
772
    'commit':                 [],
571
 
    'diff':                   [],
 
773
    'diff':                   ['file*'],
 
774
    'export':                 ['revno', 'dest'],
572
775
    'file-id':                ['filename'],
 
776
    'file-id-path':           ['filename'],
573
777
    'get-file-text':          ['text_id'],
574
778
    'get-inventory':          ['inventory_id'],
575
779
    'get-revision':           ['revision_id'],
576
780
    'get-revision-inventory': ['revision_id'],
 
781
    'help':                   ['topic?'],
 
782
    'init':                   [],
577
783
    'log':                    [],
578
784
    'lookup-revision':        ['revno'],
579
 
    'export':                 ['revno', 'dest'],
 
785
    'move':                   ['source$', 'dest'],
 
786
    'relpath':                ['filename'],
580
787
    'remove':                 ['file+'],
 
788
    'rename':                 ['from_name', 'to_name'],
 
789
    'renames':                ['dir?'],
 
790
    'root':                   ['filename?'],
581
791
    'status':                 [],
582
792
    }
583
793
 
634
844
                    else:
635
845
                        optarg = argv.pop(0)
636
846
                opts[optname] = optargfn(optarg)
637
 
                mutter("    option argument %r" % opts[optname])
638
847
            else:
639
848
                if optarg != None:
640
849
                    bailout('option %r takes no argument' % optname)
664
873
    # TODO: Need a way to express 'cp SRC... DEST', where it matches
665
874
    # all but one.
666
875
 
 
876
    # step through args and argform, allowing appropriate 0-many matches
667
877
    for ap in argform:
668
878
        argname = ap[:-1]
669
879
        if ap[-1] == '?':
670
 
            assert 0
671
 
        elif ap[-1] == '*':
672
 
            assert 0
 
880
            if args:
 
881
                argdict[argname] = args.pop(0)
 
882
        elif ap[-1] == '*': # all remaining arguments
 
883
            if args:
 
884
                argdict[argname + '_list'] = args[:]
 
885
                args = []
 
886
            else:
 
887
                argdict[argname + '_list'] = None
673
888
        elif ap[-1] == '+':
674
889
            if not args:
675
890
                bailout("command %r needs one or more %s"
677
892
            else:
678
893
                argdict[argname + '_list'] = args[:]
679
894
                args = []
 
895
        elif ap[-1] == '$': # all but one
 
896
            if len(args) < 2:
 
897
                bailout("command %r needs one or more %s"
 
898
                        % (cmd, argname.upper()))
 
899
            argdict[argname + '_list'] = args[:-1]
 
900
            args[:-1] = []                
680
901
        else:
681
902
            # just a plain arg
682
903
            argname = ap
705
926
        if 'help' in opts:
706
927
            # TODO: pass down other arguments in case they asked for
707
928
            # help on a command name?
708
 
            cmd_help()
 
929
            if args:
 
930
                cmd_help(args[0])
 
931
            else:
 
932
                cmd_help()
709
933
            return 0
710
934
        elif 'version' in opts:
711
935
            cmd_version()
715
939
        log_error('usage: bzr COMMAND\n')
716
940
        log_error('  try "bzr help"\n')
717
941
        return 1
718
 
            
 
942
 
719
943
    try:
720
944
        cmd_handler = globals()['cmd_' + cmd.replace('-', '_')]
721
945
    except KeyError:
722
946
        bailout("unknown command " + `cmd`)
723
947
 
724
 
    # TODO: special --profile option to turn on the Python profiler
 
948
    # global option
 
949
    if 'profile' in opts:
 
950
        profile = True
 
951
        del opts['profile']
 
952
    else:
 
953
        profile = False
725
954
 
726
955
    # check options are reasonable
727
956
    allowed = cmd_options.get(cmd, [])
730
959
            bailout("option %r is not allowed for command %r"
731
960
                    % (oname, cmd))
732
961
 
 
962
    # TODO: give an error if there are any mandatory options which are
 
963
    # not specified?  Or maybe there shouldn't be any "mandatory
 
964
    # options" (it is an oxymoron)
 
965
 
 
966
    # mix arguments and options into one dictionary
733
967
    cmdargs = _match_args(cmd, args)
734
 
    cmdargs.update(opts)
735
 
 
736
 
    ret = cmd_handler(**cmdargs) or 0
 
968
    for k, v in opts.items():
 
969
        cmdargs[k.replace('-', '_')] = v
 
970
 
 
971
    if profile:
 
972
        import hotshot
 
973
        prof = hotshot.Profile('.bzr.profile')
 
974
        ret = prof.runcall(cmd_handler, **cmdargs) or 0
 
975
        prof.close()
 
976
 
 
977
        import hotshot.stats
 
978
        stats = hotshot.stats.load('.bzr.profile')
 
979
        #stats.strip_dirs()
 
980
        stats.sort_stats('time')
 
981
        stats.print_stats(20)
 
982
 
 
983
        return ret
 
984
    else:
 
985
        return cmd_handler(**cmdargs) or 0
737
986
 
738
987
 
739
988
 
744
993
    ## TODO: If the arguments are wrong, give a usage message rather
745
994
    ## than just a backtrace.
746
995
 
 
996
    bzrlib.trace.create_tracefile(argv)
 
997
    
747
998
    try:
748
 
        # TODO: Lift into separate function in trace.py
749
 
        # TODO: Also show contents of /etc/lsb-release, if it can be parsed.
750
 
        #       Perhaps that should eventually go into the platform library?
751
 
        # TODO: If the file doesn't exist, add a note describing it.
752
 
        t = bzrlib.trace._tracefile
753
 
        t.write('-' * 60 + '\n')
754
 
        t.write('bzr invoked at %s\n' % format_date(time.time()))
755
 
        t.write('  by %s on %s\n' % (bzrlib.osutils.username(), socket.getfqdn()))
756
 
        t.write('  arguments: %r\n' % argv)
757
 
 
758
 
        starttime = os.times()[4]
759
 
 
760
 
        import platform
761
 
        t.write('  platform: %s\n' % platform.platform())
762
 
        t.write('  python: %s\n' % platform.python_version())
763
 
 
764
999
        ret = run_bzr(argv)
765
 
        
766
 
        times = os.times()
767
 
        mutter("finished, %.3fu/%.3fs cpu, %.3fu/%.3fs cum"
768
 
               % times[:4])
769
 
        mutter("    %.3f elapsed" % (times[4] - starttime))
770
 
 
771
1000
        return ret
772
1001
    except BzrError, e:
773
1002
        log_error('bzr: error: ' + e.args[0] + '\n')
774
1003
        if len(e.args) > 1:
775
1004
            for h in e.args[1]:
776
1005
                log_error('  ' + h + '\n')
 
1006
        traceback.print_exc(None, bzrlib.trace._tracefile)
 
1007
        log_error('(see $HOME/.bzr.log for debug information)\n')
777
1008
        return 1
778
1009
    except Exception, e:
779
1010
        log_error('bzr: exception: %s\n' % e)
780
 
        log_error('    see .bzr.log for details\n')
 
1011
        log_error('(see $HOME/.bzr.log for debug information)\n')
781
1012
        traceback.print_exc(None, bzrlib.trace._tracefile)
782
 
        traceback.print_exc(None, sys.stderr)
 
1013
        ## traceback.print_exc(None, sys.stderr)
783
1014
        return 1
784
1015
 
785
1016
    # TODO: Maybe nicer handling of IOError?